Skip to content

Instantly share code, notes, and snippets.

@dpup
Last active July 28, 2016 07:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpup/64db3034d74205a58c80 to your computer and use it in GitHub Desktop.
Save dpup/64db3034d74205a58c80 to your computer and use it in GitHub Desktop.
Code snippet for mutual exclusion lock in javascript.
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