Simulate threads using yield operator

by Subramanian 2012-09-14 12:02:12

//// 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
732
like
0
dislike
0
mail
flag

You must LOGIN to add comments