Chapter 5
Multithreading with Workers

At the start of this book, I described events as an alternative to multithreading. More precisely, events replace a specific kind of multithreading, the kind where multiple parts of an application process run simultaneously (either virtually, through interrupts, or physically on multiple CPU cores). This gets to be a problem when code running in different threads has access to the same data. Even a line as simple as

 
i++;

can be a source of pernicious Heisenbugs[44] when it allows separate threads to modify the same i at the same time. Thankfully, this kind of multithreading is impossible in JavaScript.

On the other hand, distributing tasks across multiple CPU cores is increasingly essential because those cores are no longer making the same exponential gains in efficiency, year after year, that used to be expected. So, we need multithreading. Does that mean abandoning event-based programming?

Au contraire! While running on a single thread isn’t ideal, naïvely distributing an app across multiple cores can be even worse. Multicore systems slow to a crawl when those cores have to constantly talk to each other to avoid stepping on each other’s toes. It’s much better to give each core a separate job and then sync up occasionally.

That’s precisely what workers do in JavaScript. From the master thread of your application, you tell a worker, “Go run this code in a separate thread.” The worker can send you messages (and vice versa), which take the form of (what else?) callbacks run from the event queue. In short, you interact with different threads the same way you do I/O in JavaScript.

In this chapter, we’ll look at workers in both their browser and Node manifestations, and we’ll discuss some practical applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.51.233