Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is webworker itself multi-thread?

e.g.


 worker.postMessage(data1);
 worker.postMessage(data2);

And inside the webwoker,assuming there's quantity of issues to be deal with,would worker.postMessage(data2) block before completing the data1

like image 900
Lanston Avatar asked Mar 08 '12 06:03

Lanston


People also ask

Are Webworkers multithreaded?

Web workers don't make javascript multi-threaded in any way that it wasn't before, think about it like this: you're essentially starting another single-threaded process and communicating with it, like you would be able to in node. js for example.

Are promises multithreaded?

Best Practices for JavaScript Promises JavaScript is a single-threaded language which means that a JavaScript script is only capable of executing commands, or lines of code, in a single, sequential fashion; one after another, after another.

Is Chrome JavaScript multithreaded?

As you may probably know, Javascript is single-threaded. To clarify better, this means that one single thread handles the event loop. For older browsers, the whole browser shared one single thread between all the tabs.

Is node js multithreaded true?

Node. js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.


1 Answers

A single worker executes its task in queue, i.e. one task at time. Try the following example:

<!DOCTYPE html>

<script>

var worker = new Worker('worker.js');
worker.postMessage({ task: 1, iterations: 100 }); // very slow task
worker.postMessage({ task: 2, iterations: 1 }); // very quick task
worker.onmessage = function(event) {
    console.log(event.data);
};

</script>

worker.js:

self.onmessage = function(event) {
    for (var i = 0; i < event.data.iterations * 1000 * 1000 * 10; i++) {};
    self.postMessage("Finished task " + event.data.task);
}

Ouput:

Finished task 1
Finished task 2

The tasks are always finished in order, i.e. first the slow one, then the quick one. (If the task were executed in parallel, the second task would finish first with a clear margin.)

(Just to be clear: calling postMessage always blocks in its execution context (as any function call) but effectively returns "immediately", because posting the message itself is very quick operation. That's probably not what you asked.)

Note: Chrome throws a security exception if you try to load the worker.js from local disk, works in Safari & Firefox.

like image 139
jholster Avatar answered Oct 19 '22 23:10

jholster