need help in creating an analogue of the critical section in javascript, that is, the input of the next function in the critical section should be performed after the previous one, that's what is now:

class CriticalSection { constructor() { this._flag = false; } enter() { if (!this._flag) { return new Promise((resolve, reject) => { this._flag = true; setTimeout(() => resolve(), 3000); }); } else { //здесь нужно какое-то ограничение } } leav() { this._flag = false; } } let cs = new CriticalSection(); cs.enter().then((value) => { setTimeout(() => { console.log(`1`); cs.leav(); }, 2000) }, null); cs.enter().then((value) => { setTimeout(() => { console.log(`2`); cs.leav(); }, 2000) }, null); 

  • it's not clear what kind of behavior you expect to get - Grundy
  • First, one process enters the critical section, which occupies it _flag = true, the promise returns with onFullFilled result and 1 is printed in the console, then the section is released _flag = false and the second process enters, as well as the first process and prints to console 2. The second call should wait for the completion of the first. - Anky
  • @Grundy, while you find out here, I already did :) - Qwertiy

1 answer 1

If the check to close the correct section is not required, you can replace the token with a flag.

 class CriticalSection { constructor() { this.queue = [] this.token = null } enter() { return new Promise((resolve, reject) => { if (this.token) { this.queue.push(() => resolve(this.token = {})) } else { resolve(this.token = {}) } }) } leave(token) { if (this.token !== token) { throw new Error("Leaving the wrong section") } if (this.queue.length) { this.queue.shift()() } else { this.token = null } } } let cs = new CriticalSection(); cs.enter().then(token => { console.log("Entered #1") setTimeout(() => { console.log("Timeout #1"); cs.leave(token); console.log("Left #1"); }, 2000) }, null); cs.enter().then(token => { console.log("Entered #2") setTimeout(() => { console.log("Timeout #2"); cs.leave(token); console.log("Left #2"); }, 2000) }, null); 

  • why token to drag out? Fill in at least an explanation of how this all works :) - Grundy
  • @Grundy, in the sense of outward? Why is he in the field? Well, so that the methods normally lie in the prototype. I am not a fan of underscores for private data. Or why is it even needed? Then to check that we are leaving exactly the section into which we entered. It seems even the answer is written. - Qwertiy
  • @Qwertiy, thanks for the reply, helped me figure out what was happening) - Anky