How it works...

Shared array buffers can be shared across any number of worker threads. In order to calculate portions of the result, we need to divide the results equitably between the threads. That's what the 'load-indices' case of the worker onMessage listener does.

We can use the size of the array and the total worker count to get the window size. We take the floor so that we don't go beyond the index of the array. This is also because you can't have a partial index: they are integers.

Next, we use the current worker index to get the startIndex (basically picking up where the previous worker left off). To get the end index, we need to know if this is the last worker. If not, we use the window size. If it is, we need to take all of the remaining values.

Once we have our array slice, each worker calculates the sums and averages of those portions as they would with the entire array. Then the results and the worker info are posted to the main thread.

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

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