mutex.js 417 B

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