JavaScript USES yield to simulate a multithreaded approach

  • 2020-05-17 04:46:15
  • OfStack

This article illustrates an example of how JavaScript USES yield to simulate multithreading. Share with you for your reference. The specific analysis is as follows:

The yield method is available in both python and C#, with yield you can do many things that can only be done with multiple threads.
There are version requirements for javascript: JavaScript 1.7


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) {}
}

The input result of the above code is as follows:


foo: 0
bar: 0
foo: 1
bar: 1
foo: 2
bar: 2
foo: 3
bar: 3
foo: 4
bar: 4

I hope this article is helpful for you to design javascript program.


Related articles: