Document directory
- Simple multi-threaded instance:
The HTML5 draft has been coming out for a long time. At a glance, we will find that this is a very NB standard, and it is not just something as simple as making webpages, it even covers graphics, 3D graphics, Socket communication, and multithreading. Today, let's take a look at the new Web Thread.
Web Thread is a Web Standard multithreading. In fact, in addition to using the Web Thread method, we can also use one method to simulate multithreading, that is, using ajax asynchronous requests, no matter whether we can access the file or not, a ready-made method can be triggered to process asynchronous requests. However, this method is difficult to use, and Web Thread is not only easy to use, in addition, in the future, multi-core CPUs can be used to implement true multithreading.
Let's take a look at an example. All instances are from WHATWG.
Simple multi-threaded instance:
Html section
<!DOCTYPE HTML><ptml> <pead> <title>Worker example: One-core computation</title> </pead> <body> <p>The highest prime number discovered so far is: <output id="result"></output></p> <mce:script type="text/javascript"><!-- var worker = new Worker('worker.js'); worker.onmessage = function (event) { document.getElementById('result').textContent = event.data; }; // --></mce:script> </body></ptml>
Part of JS File Name: worker. js
var n = 1;search: while (true) { n += 1; for (var i = 2; i <= Math.sqrt(n); i += 1) if (n % i == 0) continue search; // found a prime! postMessage(n);}
Explanation:
var worker = new Worker('worker.js');
In the HTML section, this line of code indicates calling the worker. js file to create a Worker instance. Note that! The parameter here is a js file, not an object. All background processing code is stored in this js file.
worker.onmessage = function (event) { document.getElementById('result').textContent = event.data; };
This part of the code is the callback function called after the ready-made program is executed. Because the code in the thread cannot directly control the DOM elements in the main process, therefore, after the thread completes, the result must be reversed to the main process for the main process to perform DOM operations.
Next let's take a look at the worker. js file.
This file is a simple program for finding even numbers. When an even number is found, the postMessage (param) method is called to return the result to the main process. param can be of any type.