|
| 1 | +# `worker-task-queue` |
| 2 | + |
| 3 | +This is a standalone implementation of the cooperative multithreading model from [Task Worklet](https://github.com/developit/task-worklet) as a zero-dependency library for Web and Node. |
| 4 | + |
| 5 | +```js |
| 6 | +import WorkerTaskQueue from 'worker-task-queue'; |
| 7 | + |
| 8 | +// Set up the worker pool |
| 9 | +const queue = new WorkerTaskQueue({ |
| 10 | + // URL/path for our worker script: |
| 11 | + workerUrl: '/path/to/worker.js', |
| 12 | + // max pool size: |
| 13 | + size: 4 |
| 14 | +}); |
| 15 | + |
| 16 | +function demo(image) { |
| 17 | + // allocates a thread in the pool doesn't have one free: |
| 18 | + const cropped = postTask('crop', image, { box: [10, 20, 30, 40] }); |
| 19 | + |
| 20 | + // subsequent tasks run on the same thread to eliminate data transfer: |
| 21 | + let large = postTask('resize', cropped, { width: 1000, height: 1000 }); |
| 22 | + large = postTask('compress', large, quality); |
| 23 | + |
| 24 | + // ... except when they get automatically parallelized by moving the input to a second thread: |
| 25 | + let thumb = postTask('resize', cropped, { width: 200, height: 200 }); |
| 26 | + thumb = postTask('compress', thumb, quality); |
| 27 | + |
| 28 | + // At this point we've only transferred one image to a background thread, |
| 29 | + // and transferred another image between two threads. |
| 30 | + |
| 31 | + // Only the final results are transferred back here, and only when we ask for them: |
| 32 | + showPreview(await large.result, await thumb.result); |
| 33 | +} |
| 34 | + |
| 35 | +demo(); |
| 36 | +``` |
0 commit comments