Skip to content

Instantly share code, notes, and snippets.

@bga
Created December 25, 2010 19:23
Show Gist options
  • Save bga/755011 to your computer and use it in GitHub Desktop.
Save bga/755011 to your computer and use it in GitHub Desktop.
/*
Shows that Mutexes, Events, and Critical Sections are available in js "threading" model too. :)
WaitForSingleObject http://msdn.microsoft.com/en-us/library/ms687032(VS.85).aspx
WaitForMultipleObjects http://msdn.microsoft.com/en-us/library/ms687025(VS.85).aspx
Event http://msdn.microsoft.com/en-us/library/ms682396(VS.85).aspx
*/
(function($G)
{
var Event = function(state)
{
if(state != null)
{
this.state = Boolean(state);
}
else
{
this.state = false;
}
this.onSetFns = [];
};
Event.prototype._set = function(state)
{
if(this.state != state)
{
this.state = state;
var i = this.onSetFns.length; while(i--)
this.onSetFns[i](this);
}
};
Event.prototype._attachListener = function(_fn)
{
if(this.onSetFns.indexOf(_fn) < 0)
this.onSetFns.push(_fn);
};
Event.prototype._detachListener = function(_fn)
{
var i = this.onSetFns.indexOf(_fn);
if(i > -1)
this.onSetFns.splice(i, 1);
};
var _waitForSingleObject = function(m, timeout, _fn)
{
var _final = function()
{
m._detachListener(_onSet)
_fn();
};
var _onSet = function(m)
{
if(m.state)
_final();
};
if(m.state)
{
_fn();
}
else
{
m._attachListener(_onSet);
if(timeout > 0 && timeout < +Infinity)
{
setTimeout(
_final,
timeout
);
}
}
};
var _waitForMultipleObject = function(ms, timeout, _fn)
{
var _final = function()
{
var i = ms.length; while(i--)
ms[i]._detachListener(_onSet);
_fn();
};
var _onSet = function(m)
{
if(m.state)
{
--n;
if(n == 0)
_final();
}
else
{
++n;
}
};
var n = 0;
var i = ms.length; while(i--)
{
if(!ms[i].state)
++n;
}
if(n == 0)
{
_fn();
}
else
{
var i = ms.length; while(i--)
ms[i]._attachListener(_onSet);
if(timeout > 0 && timeout < +Infinity)
{
setTimeout(
_final,
timeout
);
}
}
};
var _sleep = function(time, _fn)
{
setTimeout(_fn, time);
};
(function()
{
var img = new Image();
var m = new Event(false);
img.onload = function()
{
console.log('img.onload');
_sleep(1000, function()
{
m._set(true);
});
};
img.src = 'data:image/gif;base64,R0lGODlhAgACAIAAAAAAAP///yH5BAkAAAEALAAAAAACAAIAAAIDDBIFADs=';
_waitForSingleObject(m, +Infinity, function()
{
console.log('m');
});
})();
(function()
{
var img1 = new Image();
var img2 = new Image();
var m1 = new Event(false);
var m2 = new Event(false);
img1.onload = function()
{
console.log('img1.onload');
m1._set(true);
};
img2.onload = function()
{
console.log('img2.onload');
_sleep(1000, function()
{
m2._set(true);
});
};
img1.src = 'data:image/gif;base64,R0lGODlhAgACAIAAAAAAAP///yH5BAkAAAEALAAAAAACAAIAAAIDDBIFADs=';
img2.src = 'data:image/gif;base64,R0lGODlhAgACAIAAAAAAAP///yH5BAkAAAEALAAAAAACAAIAAAIDDBIFADs=';
_waitForMultipleObject([m1, m2], +Infinity, function()
{
console.log('m1, m2');
});
})();
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment