003-web worker worker Thread

Source: Internet
Author: User
Tags message queue script tag

I. About Web worker worker threads

HTML5 several advantages, including the Web worker, the goods can be known as multi-threaded, normal situation, the browser when the execution of a program will block until after the end of the run is back to normal state, and HTML5 web worker is to solve the problem.

Allows JavaScript to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM.
So it can solve two problems: first, solve the problem of blocking the program, second, improve efficiency.

Ii. examples

The most commonly used test efficiency is Fibonacci, we also have a Fibonacci performance test.

var start = (new  Date ()). GetTime (); var fibonacci =function(n) {    return n<2? N:arguments.callee (n-1) + Arguments.callee (N-2);}; Fibonacci(console.log);(new Date ()). GetTime ()- start); // Console.log played 4792

Each computer performance is different, the browser may change, 38 implementation needs to be close to 5s, two times is almost 10s.

Fibonacci (38);
Fibonacci (38);
Two executions required 9694

We introduce web Worker, improve efficiency, shorten the time difference of operation

Worker.js

var fibonacci =function(n) {    return n<2? N:arguments.callee (n-1) + Arguments.callee (N-2);}; Self.addeventlistener (function(event) {    false);

JS in the main page

//The second KindvarStart = (NewDate ()). GetTime (); //Instantiate a worker instance, the parameter must be a JavaScript scriptvarWorker =NewWorker (' Worker.js '); //Monitoring worker CommunicationWorker.addeventlistener (' message ',function(event) {Console.log (' Worker Result: ' + ((NewDate ()). GetTime ()-start));},false); //Post data to workerWorker.postmessage (38); varFibonacci =function(n) {returnN<2? N:arguments.callee (n-1) + Arguments.callee (n-2);}; //There is only one left on the main page, the other one has been transferred to the worker and executedSetTimeout (function() {Fibonacci (38); //Console.log (New Date ()). GetTime ()-start);Alert ((NewDate ()). GetTime ()-start)},100);

The result of this time is equal to two times of execution.

Three, Package

However, if you want to perform several successive executions, you cannot do this:

Worker.postmessage (38);
Worker.postmessage (38);
Worker.postmessage (38);

Because a worker is just new, it executes sequentially:

Script.js:26 5369
Script.js:9 Worker result:5374
Script.js:9 Worker result:9960
Script.js:9 Worker result:14557

Packaging:

We can simultaneously new multiple

//Third KindvarStart = (NewDate ()). GetTime (); varFibonacci =function(n) {//Instantiate a worker instance, the parameter must be a JavaScript script    varWorker =NewWorker (' Worker.js '); //Monitoring worker CommunicationWorker.addeventlistener (' message ',function(event) {Console.log (' Worker Result: ' + ((NewDate ()). GetTime ()-start)); }, false); //Post data to workerworker.postmessage (n);}; Fibonacci (38) Fibonacci (38) Fibonacci (38) Fibonacci (38)

4 results were performed:

Script.js:11 Worker result:9323
Script.js:11 Worker result:9335
Script.js:11 Worker result:9340
Script.js:11 Worker result:9350
The more visible instances, the higher the individual execution efficiency, because the new worker is also time consuming, but even this is more efficient than blocking the order in the browser.

Iv. cross-domain and script introduction

1. Worker ingestion must be the domain

The worker must pass in a script URL when instantiating, and must be in this domain, otherwise it will report a cross-domain error: This domain: http://localhost:63342/

var worker = new Worker (' http://localhost/worker.js ');

Reported security error:
Uncaught securityerror:failed to construct ' Worker ': The Script at ' http://localhost/worker.js ' cannot is accessed from Origi N ' http://localhost:63342 '.

2, in the worker code through the Importscripts method to introduce the script under any domain

Scripts in any domain can be introduced into the worker using the Importscripts method, just like the script tag in HTML

The worker introduced it.

Self.importscripts (' http://localhost/script.js ');

Console.log:Hello world! From Http://localhost/script.js

3. Synchronous asynchronous

The new Worker and the importscripts are asynchronous

Importscripts Loading is synchronous

Self.importscripts ('/script1 ');
Self.importscripts ('/script2 ');

V. Advantages and disadvantages 5.1, support API, in the worker thread, you can get the following objects

1) Navigator Object

2) Location object, read-only

3) XMLHttpRequest object, can make Ajax request

4) Settimeout/setinterval method

5) Application Cache

6) Loading other scripts through the Importscripts () method, loading the external JS script into the worker

7) Create a new web Worker

8) Addeventlistener/postmessage, with which they can communicate with the home page "You can use onmessagedirectly in the code"

5.2. Worker threads cannot get the following objects

1) Dom Object

2) Window object

3) Document Object

4) Parent Object

The specification above limits the ability to get the main thread page related objects in the worker thread, so the DOM element cannot be updated in the worker thread.

5.3. Use

1) WEB worker brings background computing power

The time-consuming part of updating data and object status is performed by web worker to improve page performance.

2) use a dedicated thread for mathematical operations

The simplest application of WEB worker is for background computing, which does not interrupt the operation of the foreground user

3) Image processing

By using the data obtained from the <canvas> or <video> elements, you can divide the image into several different regions and push them to the different workers in parallel for calculation.

4) Retrieval of large amounts of data

When you need to process large amounts of data after calling Ajax, it is important that you do this in a web worker to avoid freezing the UI thread if the amount of time it takes to process the data is significant.

5) Background Data analysis

Angular1 is the most popular complaint is its dirty check mechanism, when the scope of data too much can seriously affect performance. And Angular2 is using Webworker to move heavy computational work into the worker thread, so that the interface thread is unaffected.

Vi. principle Flow 1, classification

Two types of worker threads are defined in the Web Worker specification, namely, dedicated thread dedicated worker and shared thread, where dedicated worker can only be used for one page, and shared The worker can be shared by multiple pages, and the example in this article is a dedicated thread dedicated Worker.

2. Detailed description

Use dedicated worker's main page code main.js

var New Worker ("Task.js"); Worker.postmessage (        {            ID:1,            msg:' Hello world '        }); Worker.onmessage=function(message) {    var data = message.data;    Console.log (json.stringify (data));    Worker.terminate ();}; Worker.onerror=function(error) {    Console.log (Error.filename,error.lineno, error.message);}

Code Task.js performed by the dedicated worker

function (message) {    var data=message.data;     = ' Hi from Task.js ';    PostMessage (data);}

In the Main.js code, the worker script file name is passed in first by calling the constructor, and a new worker object is a reference to the newly created worker thread in the main thread. The Worker.postmessage () method is then called to communicate with the newly created worker thread, where a JSON object is passed in. The OnMessage event of the worker object and the callback handler for the OnError event are defined separately, and when the Woker thread returns the data, the OnMessage callback function executes, and the data is encapsulated in the message parameter's database property, invoking the worker's The Terminate () method terminates the worker thread, and when the worker thread executes an error, the onerror callback function executes, which encapsulates the file name of the wrong object, the line number of the error, and the specific error message.

In the Task.js code, the OnMessage event handler is defined, and the data passed in by the main thread is encapsulated in the Message object's Database property, and after the data processing is complete, the PostMessage method is used to communicate with the main thread. In worker code, the OnMessage event and the PostMessage method are accessible at their global scope.

2. Execution process

  

1) The worker thread is created asynchronously

When the code executes to "var worker = new Worker (Task.js ')", construct the Webcore::jsworker object (jsbbindings layer) in the kernel and the corresponding Webcore::worker object (WebCore module) , the asynchronous load process is initiated based on the initialized URL address "Task.js", and the main thread code does not block here waiting for the worker thread to load, execute the specified script file, and will immediately proceed down to the following code.

2) PostMessage message interaction is dispatched by the kernel

In Main.js, when the Woker thread is created, the PostMessage method is called immediately after the data is passed, and when the worker thread is not created, the messages emitted in the main.js are stored in a temporary message queue, and the message data in the temporary message queue is copied when the worker thread is created asynchronously The worker thread begins processing the message to the woker corresponding Workerrunloop message queue. After a round of messages, the message is added to the Workerrunloop message queue as the worker thread has been created since the communication continues.

1.3 Worker thread Data communication mode

The main thread and sub-thread data communication methods have a variety of communication content, can be text, can also be an object. It is important to note that this communication is a copy relationship, that is, it is a pass value, not an address, and the child thread modifies the communication content without affecting the main thread. In fact, the operating mechanism inside the browser is to serialize the communication content first, then send the serialized string to the child thread, which then restores it.

Binary data can also be exchanged between the main thread and the child thread, such as file, Blob, Arraybuffer, etc., and can also be sent between threads. However, sending binary data in copy mode can cause performance problems. For example, the mainline Cheng thread sends a 50MB file, and by default the browser generates a copy of the original file. To solve this problem, JavaScript allows the main thread to transfer binary data directly to the child thread, and the main thread can no longer use the data after the transfer, in order to prevent multiple threads to modify the data at the same time, this method of transferring data, called transferable Objects.

// Create a 32MB "file" and fill it. var New // 32MB  for (var i = 0; i < uint8array length; + +i) {    = i;} Worker.postmessage (Uint8array.buffer, [Uint8array.buffer]);
Vii. several tips for using Woker

(1) How many workers are used?

After determining how many workers are working at the same time to use the Web worker, there are a few things that you need to consider, such as the lack of the benefits of parallel processing, which can cause worker processing to become slower.

The general practice is to read the Navigator.hardwareconcurrency property, which represents the maximum number of tasks a machine can perform in parallel, and if this value is not available, it can give a default value, for example, 4. There is also a way to dynamically detect the number of workers, if you are interested to see: https://github.com/oftn-oswg/core-estimator

One might ask, assuming that the maximum number of parallel machines is 8, then is it possible to create only 7 workers, leaving one for the "main thread"? My advice is to see the actual situation of your application, usually the "main thread" of the page does not take long time to perform operations, most of the time is idle, then the number of workers can take 8. The Timeline (new version called performance) tool for Chrome Dev tools lets you see how each worker works and determines whether the main thread work is affected.

(2), optimize the Woker and main thread communication overhead

The data transfer between the Worker and the main thread is done by default through a structured clone (structured clone). When the amount of data is large, the cloning process can be time-consuming, which affects the execution time of the postMessage and OnMessage functions.

Solution One,

is to first serialize the object through Json.stringify, and then restore it with Json.parse after receiving it. because:stringfiy + Time-consuming < passing objects that pass strings.

// manipulating pixels    var imageData = context.createimagedata (img.width, img.height);     var New Worker ('./cal.js ');     var data = {        data:imageData.data,        width:imageData.width,        height:imageData.height    };     // convert passed arguments to strings    Work.postmessage (json.stringify (data));

Solution II,

the method of avoiding the value of cloning is to use transferable Objects, mainly using binary storage mode, using address reference to solve the real-time problem of data exchange;transferable Common data types supported by objects are Arraybuffer and imagebitmap;

 //  action pixel  var  imageData = Context.createimagedata (Img.width, img.height);  var  work = new  Worker ('./cal.js ') Span style= "color: #000000;"    >);  //  Convert to type array for pass  var  int8s =  Int8array (    Imagedata.data);  var  data = {data:int8s, width:i    Magedata.width, height:imageData.height};  //  specify PostMessage in the second argument of the Transferlist method  work.postmessage (data, [Data.data.buffer]); 

After testing, using Arraybuffer, the time required to pass the data is 1ms, which greatly improves the efficiency of transmission.

See Address:

https://yq.aliyun.com/ziliao/25009

Https://www.cnblogs.com/GongQi/p/4991380.html

Http://mp.weixin.qq.com/s/DORzY-Rgts7RAcfrbUeiDg

003-web worker worker Thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.