HTML5 and Mobile Web: Multithreading

The role of WebWork

       JavaScript to create multi-threaded environment, allowing the main thread creates Worker threads, the latter will assign some tasks to run. While the main thread running, Worker threads running in the background, the two non-interfering. Wait until Worker thread to complete computing tasks, and then return the results to the main thread.

There are several Web Worker Use Precautions

( 1 ) homologous to limit

Worker threads allocated to run the script file, the script file must be homologous with the main thread.

( 2 ) the DOM limit

Worker threads global object is located, and the main thread is not the same, DOM objects can not read the page where the main thread can not use the document, window, parent objects. However, Worker threads can navigator object and location objects.

( 3 ) communication links

Worker thread and the main thread is not in the same context, they can not communicate directly, it must be done through a message.

( 4 ) script limit

Worker threads can not execute alert () method and confirm () method, but using an AJAX request XMLHttpRequest object.

( 5 ) file limits

Worker thread was unable to read local files that can not open the machine's file system system ( File: //), it loads the script, it must come from the network.

The main thread

Create a Work thread

      The main thread uses new command, calling Worker () constructor to create a new Worker thread.

var myWorker = new Worker(jsUrl, options);

var myWorker = new Worker('worker.js', { name : 'myWorker' });

The Worker () constructor, can accept two parameters. The first parameter is the URL of the script (must comply with the same-origin policy), this parameter is required, and can only be loaded JS script, otherwise it will error. The second parameter is the configuration object optional. Its role is to specify the name of Worker, used to distinguish between multiple Worker threads.

Work main thread sends a message to the thread

worker.postMessage('Hello World');

worker.postMessage({method: 'echo', args: ['Work']});

Parameter worker.postMessage () method, the main thread is passed Worker data. It may be various types of data including binary data.

Work main thread receives messages back from the thread

worker.onmessage = function (event) {

  console.log('Received message ' + event.data);

  doSomething();

}

The main thread Close Thread Work

worker.terminate (); actively closed Worker Thread main thread.

self.close (); for closing itself inside the Worker.

Work Thread

Worker internal thread needs to have a monitor function, monitor message events.

self.addEventListener('message', function (e) {
  self.postMessage('You said: ' + e.data);
}, false);

self on behalf of the child thread itself, the global object that is sub-thread. Thus, it is equivalent to the following two kinds of writing.

// 写法一
this.addEventListener('message', function (e) {
  this.postMessage('You said: ' + e.data);
}, false);
// 写法二
addEventListener('message', function (e) {
  postMessage('You said: ' + e.data);
}, false);

Worker threads can call different methods

self.addEventListener('message', function (e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg);
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);

Worker load scripts

The method of internal Worker If you are loading other scripts, there is a special importScripts ().

importScripts('script1.js');

The method can load multiple scripts simultaneously.

importScripts('script1.js', 'script2.js');

Shared thread

Create a shared Worker needs SharedWorker constructor:

var worker = new SharedWorker('shared-worker.js');

  • Examples of shared Worker uniquely identified by a URL, you can also pass an optional name parameter to SharedWorker, for the Worker instance explicitly specify a name, the name of the Worker can create multiple instances for the same js file:
  • Worker shared borders is subject to the same origin policy, different sites can use the same name. If you want to use the same site for the same worker name will be different js error.

worker.port.postMessage(txt.value);

  •     work.port is MessagePort objects
  •     MessagePort interface represents one of the two ports MessageChannel allows sending a message from one port to another port, and they reach the listener.
  •     SharedWorker port attribute interface objects returns MessagePort communication and control for sharing the work program.

First listen for events onconnect, not onmessage event! This applies to link the event to listen, when you have a web link to begin the sharing process, this event will be called

The connection port can be referenced by the event parameter ports; onmessage This reference can attach a handler to handle the incoming message through the port, which the postMessage () method can be used to send a message back to the main thread uses the worker.

Published 349 original articles · won praise 161 · views 190 000 +

Guess you like

Origin blog.csdn.net/qq_42192693/article/details/103865363