Using yield to simulate multithreading in JavaScript
This article mainly introduces how to use yield to simulate multiple threads in JavaScript. The example analyzes the usage skills of multiple threads in javascript, which has some reference value. If you need it, you can refer to it.
This example describes how to use yield to simulate multithreading in JavaScript. Share it with you for your reference. The specific analysis is as follows:
The yield method is available in both python and C #. yield can be used to implement multiple threads.
Javascript version requirements: JavaScript 1.7
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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:
?
| 1 2 3 4 5 6 7 8 9 10 |
Foo: 0 Bar: 0 Foo: 1 Bar: 1 Foo: 2 Bar: 2 Foo: 3 Bar: 3 Foo: 4 Bar: 4 |
I hope this article will help you design javascript programs.