Node.js Worker Threads 文档: https://nodejs.org/dist/latest-v16.x/docs/api/worker_threads.html
使用 Threads.js
官方文档:https://threads.js.org/usage#typescript
安装:
yarn add threads
Demo:
// master.ts
import { spawn, Thread, Worker } from "threads"
import { Counter } from "./workers/counter"
const counter = await spawn<Counter>(new Worker("./workers/counter"))
console.log(`Initial counter: ${await counter.getCount()}`)
await counter.increment()
console.log(`Updated counter: ${await counter.getCount()}`)
await Thread.terminate(counter)
// counter.ts
import { expose } from "threads/worker"
let currentCount = 0
const counter = {
getCount() {
return currentCount
},
increment() {
return ++currentCount
},
decrement() {
return --currentCount
}
}
export type Counter = typeof counter
expose(counter)
线程池
官方文档: https://threads.js.org/usage-pool
import { spawn, Pool, Worker } from "threads"
const pool = Pool(() => spawn(new Worker("./workers/crytpo")))
const task = pool.queue(crypto => crypto.encrypt("some-password"))
task.then(result => {
// do something with the result
})
await pool.completed()
await pool.terminate()
Observable Adapter
Threads.js 内置了 observable-fns
。但与 RxJS 相比功能较少。(相关 Issue: https://github.com/andywer/threads.js/issues/278 )
配合 RxJS 使用有一个示例的项目: https://github.com/Nerdinacan/threads-observable-adapter