Simulate threads using yield operator

by Mohan 2012-09-20 22:37:11



Simulate threads using yield operator
JavaScript 1.7
//// thread definition
function Thread( name ) {

for ( var i = 0; i < 5; i++ ) {

Print(name+': '+i);
yield;
}
}

//// thread management
var threads = [];

// thread creation
threads.push( new Thread('foo') );
threads.push( new Thread('bar') );

// scheduler
while (threads.length) {

var thread = threads.shift();
try {
thread.next();
threads.push(thread);
} catch(ex if ex instanceof StopIteration) {}
}
prints:
foo: 0
bar: 0
foo: 1
bar: 1
foo: 2
bar: 2
foo: 3
bar: 3
foo: 4
bar: 4



721
like
0
dislike
0
mail
flag

You must LOGIN to add comments