Web Worker Multithreading

Posted by velanzia on Wed, 31 Jul 2019 02:40:12 +0200

Web Worker Thread Processing

1. The browser arranges all events in the event queue through the operating system (e.g. you buy food in a window and need to queue); the browser uses single thread to process events in the queue and execute user code (i.e. single thread; except web workers).

Therefore, browsers can only handle one of these tasks at a time, and any task can prevent the execution of other tasks.

2. How to judge that the code is "fast enough"? The user experience of 0.1 seconds is that the user can operate freely without waiting; the delay of 0.2-1.0 seconds will be noticed by the user; if it exceeds 1 second, the user will feel unfluent; if it exceeds 10 seconds, the user will be very depressed.

Manual code detection:

<div onclick="jsTest">...</div>

function jsTest(){
  var start  = new Date().getMilliseconds();
//Here's a very expensive code
var time = stop - start;
alert("jsTest() executes in " + time + " milliseconds");        
}

fireBug Performance Analyser

Specific code can be added to the measured code to collect performance statistics, or specific execution code can be checked in real time at a specific time to monitor run time. The latter analyses the buy-on-demand performance with little distortion, but the quality of the data obtained will be the first point. You can go through (click the "Send" button)

Then the Star firebug Performance Analyser looks at the time-consuming.

3-Thread Processing

Use multithreading to strip expensive code from threads that interact with users. The basic problem with multithreading is that different threads can access and modify the same address. (What we need is a multitasking approach like multithreading without the danger of intrusion between threads.)

4 Web Workers

Let's take a look at how to use the Web Workers API to de-encapsulate values. The following shows how to create and start Worker:

//Create and start executing worker
var worker = new Worker("js/decrypt.js");

//Register the event handler to execute when the worker sends information to the main thread
worker.onmessage = function(e){
  alert("The decrypted value is" + e.data);
}

//Send information to worker, which refers to the value to be decrypted
worker.postMessage(getValueToDecrypt());

//The following is the content in js/decrypt.js:
//Register a handler that receives information from the main thread
onmessage = function(e){
  //Get the data coming in
  var valueToDecrypt = e.data;
  //TODO: Implementing decryption here
  //Return the value to the main thread
  this.postMessage(decryptedValue);
}

Any expensive (for example, long-running) javascript operation on a page should be delegated to Worker; it can run faster.

5. If the browser you use does not support the Web Worker API, you can use the Gears Worker API; the code is as follows:

//Create worker Pool, which generates Worker
var workerPool = google.gears.factory.create('beta.workpool');

//Register the event handler, which receives information from Worker
workerPool.onmessage = function(ignorel, ignorel2, e){
  alert("The decrypted value is" + e.body);
}

//Create Worker
var workerId = workerPool.createWorkerFromUrl("js/decrypt.js");

//Send information to this Worker
workerPool.sendMessage(getValueToDecrpt(). workerId);

//The following is the Gears version of js/decrypt.js:

var workerPool = google.gears.workerPool;
workerPool.onmessage = function(ignorel, ignorel2, e){
  //Get the passed data
  var getValueToDecrpt = e.body;
  //TODO: Encapsulation here

  //Return the value to the main thread
  workerPool.sendMessage(decryptedValue, e.sender);
}

6. Timer

var funState = {};
function expensiveOperation(){
  var startTime = new Date().getMilliseconds();
  while ((new Date().getMilliseconds() - startTime) < 80){
    //TODO: It performs expensive operations in the following ways:
    //It performs 80 milliseconds of work in an iterated chunk.
    //Then modify the state of the function's external "function".
  }
  if(!funState.isFinished){
    //Exit for 10 seconds and then execute expensive operation.
    //Experiments are carried out with larger values to achieve an appropriate balance between Ui response and performance.
    setTimeout(expensiveOperation(),10);
  }
}

XHRHttpRequest: XHR has synchronous and asynchronous execution modes. In asynchronous mode, XHR is essentially a Web Worker with a dedicated API.

In synchronization mode, XHR causes the user interface to have the same persistent latency as XHR takes to send his request and parse the response from the server. It can also lead to unpredictable and user-intolerable interface delays.

Topics: PHP Google Javascript