[whatwg] WebWorkers vs. Threads

Paweł Stradomski pstradomski at gmail.com
Wed Aug 13 05:24:59 PDT 2008


W liście Shannon z dnia środa 13 sierpnia 2008:

> He wasn't against WebWorkers, he was, as you say,  against full
> threading (with all the mutexes and locks etc... exposed to the JS
> author). I can't find the reference site but it doesn't really matter
> except from the point of view that many people (including myself) aren't
> convinced a full pthread -like API is the way to go either. I just don't
> see why locking can't be transparently handled by the interpreter given
> that the language only interacts with true memory registers indirectly.
Such implicit/transparent/automatic locking is in fact impossible. There are 
always cases where the developer must manually control locking. The only 
thread-safe way to lock implicitly would be to obtain a lock when handle to 
shared object is retrieved and released when the reference is dropped/garbage 
collected - locking on single read/write operation is not sufficient. In 
order to avoid deadlocks it would be neccessary to lock access globally, for 
all possible shared variables, which is not feasible. This is also the reason 
setTimeout/setInterval callbacks are run in the main thread - and switching 
to coroutines would not help here.

So, if we want the threads to be able to share variables directly, we need at 
least some basic synchronization prymitives (critical sections, akin to 
Java 'synchronized' blocks would be probably easiest).




>
> In other news...
>
> Despite the feedback I've been given I find the examples of potential
> applications pretty unconvincing. Most involve creating workers to wait
> on or manage events like downloads or DB access. 

So an example from me. Suppose i need to download a few (20-30) JSON data sets 
from some URL and then do some processing before displaying them.

Naïve pseudocode:

button.onclick = function() {
   for (var i = 0; i < 20; i++) {
        synchronousRequest(i);
   }

   processData();

   updateDOM();

   return;
}

The problem is that with such a construct I'd block the only thread in JS, so 
all other events will not be handled until the return statement.

So, with current code, I need to do:

button.onclick = function() {
  var i = 0;

  var handler = function(data) {
     i = i+1;
     if (i == 20) {
         processData();
         updateDom();
     } else {
         asyncRequest(i, handler);
     }
  }

  asyncRequest(i, handler);
}

This way I do not block on network I/O, but  still block on processData. With 
real threads I would be able to perform the data processing and then notify 
the main thread that data is processed and ready - so the main thread would 
only updateDOM().


-- 
Paweł Stradomski



More information about the whatwg mailing list