Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/blacha/wtrpc
Typesafe worker threads
https://github.com/blacha/wtrpc
Last synced: 14 days ago
JSON representation
Typesafe worker threads
- Host: GitHub
- URL: https://github.com/blacha/wtrpc
- Owner: blacha
- Created: 2022-08-25T06:56:21.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-09-30T03:39:46.000Z (4 months ago)
- Last Synced: 2024-12-15T21:42:31.592Z (about 1 month ago)
- Language: TypeScript
- Size: 127 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# wtrpc
Type safe node js worker threads
Define a contract `contract.ts`
```typescript
type RpcContract = {
scan: (req: {pid: number, pattern: string}) => number[]
}
```Implement the contract as a worker
`worker.ts`
```typescript
import { WorkerRpc } from '@wtrpc/core'
import { RpcContract } from './contract.js'
import { parentPort } from 'node:worker_threads';const worker = new WorkerRpc({
scan(req: {pid: number, pattern: string}): number[] {
return [-1]
}
})// Bind the worker to the worker_thread parent port if it exists
if (parentPort) worker.bind(parentPort);
````pool.ts`
```typescript
import { WorkerRpcPool } from '@wtrpc/core'
import { RpcContract } from './contract.js'const workerUrl = new URL('./worker.js', import.meta.url);
const threadCount = os.cpus().length;const pool = new WorkerRpcPool(threadCount, workerUrl);
// Run the task on the worker thread pool
const tasks = [
{ pid: 37 },
{ pid: 50 },
{ pid: 99 }
]const offsets = tasks.map(t => pool.run('scan', { pid: t.pid, pattern: '00 ?? 00 ?? 07' }));
const results = await Promise.all(offsets)
// [-1]
```