Search code examples
multithreadingconcurrencyparallel-processingprocessweb-worker

Web-Wokers, Concurrent or Parallel?


There are many blogs on web-workers, but it seems like people do not understand the difference of concurrency and parallelism. Some writes it to be parallel execution, and rest of them writes it to be concurrent.

Anyone who can help me with this confusion?


Solution

  • It sounds like there might be an issue understanding the difference between both terms...

    Instead of paraphrasing an existing answer, I invite you to read that one from Mason Wheeler.
    Basically, concurrency is a state, parallelism is one of the means to achieve this state.

    Hard to comment on those "blogs" you're talking about without being able to read them, but if you want to be safe then say that Worker context run in concurrency to window's context.

    How this concurrency is achieved will vary. On a multi-threaded CPU, chances are high that it will actually be in parallel, but even then, it's not a given.

    You could for instance launch more Workers than the number of threads available:

    for( let i = 0; i <= navigator.hardwareConcurrency; i++ ) {
      const worker = new Worker('worker-script.js');
    }
    

    Here at least two contexts will share the same CPU thread, meaning these contexts will not run in parallel, but probably by task switching.


    On a separate note, even if both contexts do run in parallel some operations will require that one context waits for the other to be free.
    For instance, at init the worker's message port has to be "entangled" with the temporary ports the main thread has created so it can store the incoming messages until the Worker is ready to handle them. This entanglement requires that Worker waits for the parent's context to be free so it can pass it.
    An other example is with OffscreenCanvas where at least in Chrome's implementation, the Worker has to wait for the main thread to be free so it can access the same GPU context.