Skip to content

Instantly share code, notes, and snippets.

@dogles
Last active August 29, 2015 13:56
Show Gist options
  • Save dogles/8936012 to your computer and use it in GitHub Desktop.
Save dogles/8936012 to your computer and use it in GitHub Desktop.
/** The function should be invoke when the thread exit. The execution only continues if all child threads have invoked their `JoinFunction`. */
typedef JoinFunction = (Void->Void)->Void;
/**
Fork threads for every element in <code>threadIdentifiers</code>.
@param handler The callback function invoked for each element in <code>threadIdentifiers</code>.
The <code>handler</code> can receive two parameters:
the element in <code>threadIdentifiers</code> and the <code>JoinFunction</code>.
**/
public static function fork<Identifier>(
threadIdentifiers: Iterable<Identifier>,
handler:Identifier->JoinFunction->Void):Void
{
if (Lambda.empty(threadIdentifiers))
{
throw "threadIdentifiers must not be empty!";
}
var counter = 1;
var quickJoinHandler = null;
for (id in threadIdentifiers)
{
counter++;
var isJoined = false;
handler(id, function(joinHandler)
{
if (isJoined)
{
throw "Cannot join twice in one thread!";
}
else
{
isJoined = true;
if (--counter == 0)
{
joinHandler();
}
else
{
quickJoinHandler = joinHandler;
}
}
});
}
if (--counter == 0)
{
quickJoinHandler();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment