Skip to content

Instantly share code, notes, and snippets.

@pmj
Created March 17, 2010 14:17
Show Gist options
  • Save pmj/335271 to your computer and use it in GitHub Desktop.
Save pmj/335271 to your computer and use it in GitHub Desktop.
/**
* Runs the given function while locking (synchronising on) the specified object.
*
* This uses Rhino's sync() function, but is a lot more flexible, allowing
* unbound functions and closures. May of course be nested, but beware of deadlocks.
* @param {Object} obj JavaScript object to be locked.
* @param {Function} fn The function to call from within a synchronised block.
* @param [args...] Any number of additional arguments to pass to fn.
* @returns The value returned from calling fn.
*
* @example
* function test(x) {
* print("entry");
* java.lang.Thread.sleep(x * 1000);
* print("exit");
* }
* var o = {};
* spawn(function(){ locking(o, test, 3); });
* spawn(function(){ locking(o, test, 3); });
*/
function locking(obj, fn) {
var args = Array.prototype.slice.call(arguments, 2);
var locked = sync(function() {
return fn.apply(null, args);
});
return locked.apply(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment