like-thread 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +55 -0
- package/index.js +369 -0
- package/package.json +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Lucas Barrena
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# like-thread
|
|
2
|
+
|
|
3
|
+
Simple threads for Node.js
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm i like-thread
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
Create a thread and reuse it:
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
import Thread from 'like-thread'
|
|
15
|
+
|
|
16
|
+
const thread = new Thread(function (a, b) {
|
|
17
|
+
return a + b
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
console.log(await thread.call(1, 1)) // => 2
|
|
21
|
+
console.log(await thread.call(2, 2)) // => 4
|
|
22
|
+
|
|
23
|
+
await thread.close()
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Iterators:
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
const thread = new Thread(async function * (n) {
|
|
30
|
+
for (let i = 1; i <= n; i++) {
|
|
31
|
+
yield i
|
|
32
|
+
}
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
for await (const value of thread.call(3)) {
|
|
36
|
+
console.log(value) // 1, 2, 3
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
await thread.close()
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
New temporary thread on each call:
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
console.log(await Thread.go([1, 1], sum)) // => 2
|
|
46
|
+
console.log(await Thread.go([2, 2], sum)) // => 4
|
|
47
|
+
|
|
48
|
+
function sum (a, b) {
|
|
49
|
+
return a + b
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## License
|
|
54
|
+
|
|
55
|
+
MIT
|
package/index.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
const { isMainThread, Worker, workerData, parentPort } = require('worker_threads')
|
|
2
|
+
|
|
3
|
+
if (isMainThread) {
|
|
4
|
+
const promiseWithResolvers = require('promise-resolvers')
|
|
5
|
+
|
|
6
|
+
module.exports = class Thread {
|
|
7
|
+
static go (args, fn) {
|
|
8
|
+
const thread = new this(fn, args)
|
|
9
|
+
|
|
10
|
+
if (!thread.isGenerator) {
|
|
11
|
+
const value = thread.call(...args)
|
|
12
|
+
|
|
13
|
+
return value.finally(() => thread.close())
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const iterator = thread.call(...args)
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
[Symbol.asyncIterator] () {
|
|
20
|
+
return this
|
|
21
|
+
},
|
|
22
|
+
|
|
23
|
+
async next () {
|
|
24
|
+
const result = await iterator.next()
|
|
25
|
+
|
|
26
|
+
if (result.done) {
|
|
27
|
+
await thread.close()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return result
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
async return (value) {
|
|
34
|
+
try {
|
|
35
|
+
return await iterator.return(value)
|
|
36
|
+
} finally {
|
|
37
|
+
await thread.close()
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
constructor (fn, opts = {}) {
|
|
44
|
+
const workerData = {
|
|
45
|
+
fn: fn.toString()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const entrypoint = workerData.fn.match(/(async )?function( ?\* ?)? ([a-zA-Z0-9]+)? ?\(([^)]*?)\)/i)
|
|
49
|
+
|
|
50
|
+
this.isAsync = !!entrypoint[1]
|
|
51
|
+
this.isGenerator = !!entrypoint[2]
|
|
52
|
+
|
|
53
|
+
this.worker = new Worker(__filename, { workerData, argv: opts.argv || null })
|
|
54
|
+
|
|
55
|
+
this.id = 1
|
|
56
|
+
this.requests = new Map()
|
|
57
|
+
|
|
58
|
+
this.worker.on('message', this._onMessage.bind(this))
|
|
59
|
+
|
|
60
|
+
this.promise = new Promise((resolve, reject) => {
|
|
61
|
+
let error = null
|
|
62
|
+
|
|
63
|
+
this.worker.on('error', err => {
|
|
64
|
+
error = err
|
|
65
|
+
|
|
66
|
+
for (const [id, req] of this.requests) {
|
|
67
|
+
this.requests.delete(id)
|
|
68
|
+
|
|
69
|
+
if (req.resolver) {
|
|
70
|
+
req.resolver.reject(err)
|
|
71
|
+
} else {
|
|
72
|
+
req.iterator.fail(err)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
reject(err)
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
this.worker.on('exit', (exitCode, signal) => {
|
|
80
|
+
if (error) return
|
|
81
|
+
|
|
82
|
+
const err = new Error('Worker closed (' + exitCode + ' and ' + signal + ')')
|
|
83
|
+
|
|
84
|
+
for (const [id, req] of this.requests) {
|
|
85
|
+
this.requests.delete(id)
|
|
86
|
+
|
|
87
|
+
if (req.resolver) {
|
|
88
|
+
req.resolver.reject(err)
|
|
89
|
+
} else {
|
|
90
|
+
req.iterator.fail(err)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const success = exitCode === 0 || exitCode === 130 || signal === 'SIGINT' || signal === 'SIGTERM' || signal === 'SIGHUP'
|
|
95
|
+
|
|
96
|
+
if (success) {
|
|
97
|
+
resolve()
|
|
98
|
+
} else {
|
|
99
|
+
reject(err)
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
_onMessage (msg) {
|
|
106
|
+
const req = this.requests.get(msg.id)
|
|
107
|
+
|
|
108
|
+
if (!req) {
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// console.log('_onMessage', msg, !!req.iterator ? 'iterator' : 'promise')
|
|
113
|
+
|
|
114
|
+
if (msg.error) {
|
|
115
|
+
this.requests.delete(msg.id)
|
|
116
|
+
|
|
117
|
+
const err = new Error(msg.error)
|
|
118
|
+
|
|
119
|
+
if (req.resolver) {
|
|
120
|
+
req.resolver.reject(err)
|
|
121
|
+
} else {
|
|
122
|
+
req.iterator.fail(err)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// msg.value can be a falsy value like 0 or null
|
|
129
|
+
if (msg.v) {
|
|
130
|
+
if (req.resolver) {
|
|
131
|
+
req.resolver.resolve(msg.value)
|
|
132
|
+
} else {
|
|
133
|
+
req.iterator.push(msg.value)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (msg.done) {
|
|
140
|
+
this.requests.delete(msg.id)
|
|
141
|
+
|
|
142
|
+
req.iterator.close()
|
|
143
|
+
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
this.requests.delete(msg.id)
|
|
148
|
+
|
|
149
|
+
if (req.resolver) {
|
|
150
|
+
req.resolver.reject(new Error('Invalid message'))
|
|
151
|
+
} else {
|
|
152
|
+
req.iterator.fail(new Error('Invalid message'))
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
call (...args) {
|
|
157
|
+
if (this.id === 0xffffffff) {
|
|
158
|
+
this.id = 1
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const id = this.id++
|
|
162
|
+
|
|
163
|
+
const sab = new SharedArrayBuffer(4)
|
|
164
|
+
const control = new Int32Array(sab)
|
|
165
|
+
|
|
166
|
+
Atomics.store(control, 0, 0)
|
|
167
|
+
|
|
168
|
+
if (!this.isGenerator) {
|
|
169
|
+
const resolver = promiseWithResolvers()
|
|
170
|
+
|
|
171
|
+
this.requests.set(id, { resolver })
|
|
172
|
+
|
|
173
|
+
this.worker.postMessage({ id, args, sab })
|
|
174
|
+
|
|
175
|
+
return resolver.promise
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const iterator = {
|
|
179
|
+
resolver: promiseWithResolvers(),
|
|
180
|
+
queue: [],
|
|
181
|
+
closed: false,
|
|
182
|
+
push: function (value) {
|
|
183
|
+
if (this.closed) {
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
this.queue.push({ value, done: false })
|
|
188
|
+
this.resolver.resolve()
|
|
189
|
+
},
|
|
190
|
+
fail: function (err) {
|
|
191
|
+
if (this.closed) {
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
this.closed = true
|
|
196
|
+
this.resolver.resolve(err)
|
|
197
|
+
},
|
|
198
|
+
close: function () {
|
|
199
|
+
if (this.closed) {
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
this.closed = true
|
|
204
|
+
this.resolver.resolve()
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
this.requests.set(id, { iterator })
|
|
209
|
+
|
|
210
|
+
this.worker.postMessage({ id, args, sab })
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
[Symbol.asyncIterator] () {
|
|
214
|
+
return this
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
async next () {
|
|
218
|
+
Atomics.store(control, 0, 1)
|
|
219
|
+
Atomics.notify(control, 0, 1)
|
|
220
|
+
|
|
221
|
+
const err = await iterator.resolver.promise
|
|
222
|
+
|
|
223
|
+
if (err) {
|
|
224
|
+
throw err
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (iterator.queue.length === 0) {
|
|
228
|
+
return { done: true }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (iterator.queue.length === 1) {
|
|
232
|
+
iterator.resolver = promiseWithResolvers()
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const item = iterator.queue.shift()
|
|
236
|
+
|
|
237
|
+
return item
|
|
238
|
+
},
|
|
239
|
+
|
|
240
|
+
return: () => {
|
|
241
|
+
iterator.closed = true
|
|
242
|
+
|
|
243
|
+
Atomics.store(control, 0, 2)
|
|
244
|
+
Atomics.notify(control, 0, 1)
|
|
245
|
+
|
|
246
|
+
// this.worker.postMessage({ id, command: 'stop' })
|
|
247
|
+
// return
|
|
248
|
+
|
|
249
|
+
// iterator.queue.length = 0
|
|
250
|
+
// iterator.resolver.resolve()
|
|
251
|
+
|
|
252
|
+
return Promise.resolve({ done: true })
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async * [Symbol.asyncIterator] () {
|
|
258
|
+
for await (const [value] of this.iterator) {
|
|
259
|
+
yield value
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async next () {
|
|
264
|
+
const { done, value } = await this.iterator.next()
|
|
265
|
+
|
|
266
|
+
return { done, value: done ? undefined : value[0] }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return () {
|
|
270
|
+
return this.iterator.return()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
then (onFulfilled, onRejected) {
|
|
274
|
+
return this.promise.then(onFulfilled, onRejected)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
catch (onRejected) {
|
|
278
|
+
return this.promise.catch(onRejected)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
finally (onFinally) {
|
|
282
|
+
return this.promise.finally(onFinally)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async close () {
|
|
286
|
+
this.worker.postMessage({ command: 'exit' })
|
|
287
|
+
|
|
288
|
+
await this.promise
|
|
289
|
+
|
|
290
|
+
// await this.worker.terminate()
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} else {
|
|
294
|
+
const entrypoint = workerData.fn.match(/(async )?function( ?\* ?)? ([a-zA-Z0-9]+)? ?\(([^)]*?)\)/i)
|
|
295
|
+
|
|
296
|
+
const isAsync = !!entrypoint[1]
|
|
297
|
+
const isGenerator = !!entrypoint[2]
|
|
298
|
+
const functionName = entrypoint[3] || '_WORKER_MAIN_'
|
|
299
|
+
const functionArgs = entrypoint[4] || ''
|
|
300
|
+
|
|
301
|
+
const fn = workerData.fn.replace(entrypoint[0], (isAsync ? 'async ' : '') + 'function ' + (isGenerator ? '* ' : '') + functionName + ' (' + (functionArgs) + ')')
|
|
302
|
+
|
|
303
|
+
parentPort.on('message', async (msg) => {
|
|
304
|
+
if (msg.command === 'exit') {
|
|
305
|
+
process.exit(0)
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
try {
|
|
310
|
+
// TODO: Optimize by creating the function only once by fixing the args
|
|
311
|
+
const source = fn + '\n\nmodule.exports = ' + functionName + '(...' + JSON.stringify(msg.args || []) + ')'
|
|
312
|
+
|
|
313
|
+
const wrap = new Function('require', '__dirname', '__filename', 'module', 'exports', 'parentPort', source) // eslint-disable-line no-new-func
|
|
314
|
+
|
|
315
|
+
const mod = { exports: {} }
|
|
316
|
+
|
|
317
|
+
wrap(require, __dirname, __filename, mod, mod.exports, parentPort)
|
|
318
|
+
|
|
319
|
+
const out = mod.exports
|
|
320
|
+
|
|
321
|
+
if (isGenerator) {
|
|
322
|
+
const control = new Int32Array(msg.sab)
|
|
323
|
+
const it = out[Symbol.asyncIterator] ? out[Symbol.asyncIterator]() : out[Symbol.iterator]()
|
|
324
|
+
|
|
325
|
+
while (true) {
|
|
326
|
+
while (Atomics.load(control, 0) === 0) {
|
|
327
|
+
const res = Atomics.waitAsync(control, 0, 0)
|
|
328
|
+
|
|
329
|
+
if (res.async) {
|
|
330
|
+
await res.value
|
|
331
|
+
} else {
|
|
332
|
+
break
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (Atomics.load(control, 0) === 2) {
|
|
337
|
+
break
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const { value, done } = await it.next()
|
|
341
|
+
|
|
342
|
+
Atomics.store(control, 0, 0)
|
|
343
|
+
|
|
344
|
+
if (done) {
|
|
345
|
+
parentPort.postMessage({ id: msg.id, done: true })
|
|
346
|
+
break
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Keep "v" because "value" can be falsy like 0 or null
|
|
350
|
+
parentPort.postMessage({ id: msg.id, value, v: true })
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (isAsync) {
|
|
357
|
+
const value = await out
|
|
358
|
+
|
|
359
|
+
parentPort.postMessage({ id: msg.id, value, v: true })
|
|
360
|
+
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
parentPort.postMessage({ id: msg.id, value: out, v: true })
|
|
365
|
+
} catch (err) {
|
|
366
|
+
parentPort.postMessage({ id: msg.id, error: err })
|
|
367
|
+
}
|
|
368
|
+
})
|
|
369
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "like-thread",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"files": [],
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "standard && brittle test.js"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/lukks/like-thread.git"
|
|
13
|
+
},
|
|
14
|
+
"author": "Lucas Barrena (LuKks)",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/lukks/like-thread/issues"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/lukks/like-thread#readme",
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"brittle": "^3.3.2",
|
|
22
|
+
"same-object": "^1.0.2",
|
|
23
|
+
"standard": "^17.1.0"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"promise-resolvers": "^1.0.0"
|
|
27
|
+
}
|
|
28
|
+
}
|