. What WEB worker is
Web Worker is part of the HTML5 standard, which defines a set of APIs that allow a piece of JavaScript program to run in another thread outside the main thread. 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.
1.1 API Get started quickly
Use dedicated worker's main page code main.js
123456789101112131415 |
var worker = 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
12345 |
onmessage = function(message){ var Data=message. Data; data. msg = ' Hi from Task.js '; postMessage(data); } |
In the Main.js code, first by calling the constructor, passing in the worker script file name and creating a new worker object, in my understanding, this object is a reference to the new 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.
1.2 Worker thread Execution process
The process of loading and executing a worker thread is webkit by looking up the data as shown in
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.
123456 |
//Create a 32MB "file" and fill it.var uint8array = new uint8array (1024* 1024*32) //32MB for (var i = 0; i < uint8array . Length; ++i) { Uint8array[i] = i; }worker. PostMessage(uint8array. Buffer, [uint8array. Buffer]); |
1.4 API Advanced
In the worker thread, the following objects can be obtained
1) Navigator Object
2) Location object, read-only
3) XMLHttpRequest Object
4) Settimeout/setinterval method
5) Application Cache
6) Loading additional scripts through the Importscripts () method
7) Create a new web Worker
The worker thread 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.
2. Familiar worker model
I always had a similar feeling when I was learning web worker. In our previous learning experience, we learned about swing workers in the Java Swing GUI library, and we can look at the application of the worker model in swing.
2.1 Swing Event Distribution model
Like other GUI libraries such as WINFORM/WPF, Swing is a single-threaded programming model based on event queuing. Swing waits for the GUI request to be executed in an event queue eventqueue, and the eventqueue distribution mechanism is managed by a separate thread called the event Dispatch thread (Eventdispatchthread), responsible for drawing and updating the GUI components. The distribution model for this event is as follows:
One problem with the swing single-threaded model is that if you perform too many operations on the event dispatch thread, the GUI interface will stop and the system will respond and operate very slowly.
Since the event dispatch thread is designed to handle GUI events, we should only place the code that is related to the GUI event processing in the event dispatch thread. Other interface-independent code should be executed in other Java threads. In this way, we still use swing's single-threaded programming model in the event handling of swing, while other business operations use the multithreaded programming model, which can greatly improve the responsiveness and speed of the swing program and fully utilize the advantages of Java multithreaded programming.
2.2 Swing Worker
Java SE 6 provides the Javax.swing.SwingWorker class, which is designed for situations where you need to run long-running tasks in a background thread and provides updates to the UI after completion or during processing.
Suppose we click the Download button in the UI interface, in the event handler function of the button, we need to load an icon image, and after the image is loaded, the icon is displayed in the UI interface.
12345678910111213 |
swingworker testworker = new swingworker<Icon , Void >(){ @Override protected Icon doinbackground() throws Exception { icon icon = retrieveimage(strimageurl); return icon; } protected void done (){ icon icon= get(); lblimage. SetIcon(icon); //lblimage can be passed through the constructor function } } testworker. Execute(); |
In the above code, we created an SwingWorker instance object in the button's event handler. When you call the constructor, you specify that the first generic parameter is icon, which is a custom type, which represents an icon picture object. This generic parameter is specified to specify the return value of the Doinbackground () method and is obtained in the Done () method.
The Doinbackground method executes as part of the worker thread, which is responsible for completing the basic tasks of the thread and taking the return value as the result of the thread's execution. After the Doinbackground method completes, SwingWorker calls the Done method. If the task needs to be completed, use the worker thread to perform the results to update the GUI components or do some cleanup work, you can override the done method to complete them. Using the Get method of SwingWorker to get the results of the Doinbackground method, the Done method is the best place to call the Get method because it is known that the thread task is complete and swingworker activates the done method on the EDT. Therefore, you can safely interact with any GUI component within this method. The Execute method is executed asynchronously, and it is immediately returned to the caller. After the Execute method executes, the EDT proceeds immediately.
2.3 Webworker vs SwingWorker
Swing workers also have some other methods that are not discussed here. We can combine the web Worker to compare the similarities and differences.
The programming model is the same, both in the main thread, the time-consuming work to the work thread to complete the asynchronous, so as to avoid the main thread blocking.
The two threads communication mechanism is different, the WEB worker thread communication is restricted strictly, only can communicate through the PostMessage method, and the parameter passing is the value pass, no reference passing; Swing worker parameters are passed flexibly, in the case The Doinbackground method of Testworker directly refers to the Strimageurl variable, but it is not recommended, but a new class should be defined to inherit from SwingWorker, and the Imgurl variable is passed in the constructor. The variables are then passed in the instantiated worker thread.
Unlike the update restrictions on the UI interface, WEB worker prohibits manipulating dom elements in worker threads, so it is not possible to update the ui;swing worker in the worker to allow the UI to be updated in the done method, and there is no violation of Swing's event distribution model. Because the done method is eventually activated on the EDT, the event distribution model is still followed.
3. What the Web worker brings
Finally, to summarize what the Web worker has brought to JavaScript, in the course of learning, I do not endorse the idea that Web worker is a multithreaded programming capability for JavaScript.
3.1 WEB worker brings background computing power
The WEB worker itself is implemented by WebKit multithreading, but it does not bring a multithreaded programming feature to the Javasctipt language, and we still cannot create and manage a thread in JavaScript code, or actively control the characteristics of synchronization and locking between threads.
In my opinion, WEB worker is the application of the worker programming model in the browser-side JavaScript language. The browser runs like other GUI programs, and the core logic is like this infinite loop:
1234 |
while(true){ 1 Updates data and object states /c7> 2 rendering visual UI } |
Before a web worker, the JavaScript execution engine can only accomplish both tasks in a single-threaded environment. In other typical GUI frameworks, such as the previous swing library, swing workers have been introduced to solve a lot of computational blocking problems with UI rendering. The introduction of WEB worker is a reference to the worker programming model, which brings the ability of background computation to single-threaded JavaScript.
3.2 Web Worker Typical application scenario
Now that the Web worker has the background computing power for browser-side JavaScript, we can take advantage of this ability to put the time-consuming portion of the first "Update data and Object state" in an infinite loop to web worker execution to improve page performance.
Some typical application scenarios are as follows
1) 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
2) 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.
3) 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.
4) Background Data analysis
Since we have more potential CPU time when using Web worker, we can now consider new scenarios in JavaScript. For example, we can imagine processing user input in real time without compromising the UI experience. With this possibility, we can imagine an app like Word (Office Web Apps Suite): When the user is typing, the background is searched in the dictionary, which helps the user to automatically correct the error and so on.
What WEB worker is