Last active
April 5, 2025 19:38
-
-
Save dpup/64db3034d74205a58c80 to your computer and use it in GitHub Desktop.
Code snippet for mutual exclusion lock in javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FastMutex.prototype.runInLock = function (callback, opt_context) { | |
this._setX() | |
if (!this._isLockAvailable()) { | |
this._retry(callback, opt_context) | |
return | |
} | |
this._setY() | |
if (this._getX() != this._clientId) { | |
window.setTimeout(function () { | |
if (this.hasLock()) this._execute(callback, opt_context) | |
else this._retry(callback, opt_context) | |
}.bind(this), Math.round(Math.random() * 100)) | |
} else { | |
this._execute(callback, opt_context) | |
} | |
} | |
FastMutex.prototype._execute = function (callback, opt_context) { | |
var rv | |
try { | |
rv = callback.call(opt_context) | |
} finally { | |
if (rv instanceof goog.async.Deferred) { | |
rv.addFinally(this._clearLock, this) | |
} else { | |
this._clearLock() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment