在python和C#中都有yield方法,通过yield可以实现很多多线程才能实现的功能。
对javascript有版本要求:JavaScript 1.7
//// thread definition,http://www.75271.com
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) {}
}
上面代码输入结果如下:
foo: 0 bar: 0 foo: 1 bar: 1 foo: 2 bar: 2 foo: 3 bar: 3 foo: 4 bar: 4
