mutex.js 418 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. class Mutex {
  3. constructor() {
  4. this._locked = false;
  5. this._queue = [];
  6. }
  7. lock(fn) {
  8. if (this._locked) {
  9. this._queue.push(fn);
  10. return;
  11. }
  12. this._locked = true;
  13. fn();
  14. }
  15. unlock() {
  16. if (!this._locked) return;
  17. const next = this._queue.shift();
  18. if (next) {
  19. next();
  20. } else {
  21. this._locked = false;
  22. }
  23. }
  24. }
  25. module.exports = Mutex;