UNPKG

2.34 kBJavaScriptView Raw
1/**
2 * Workers
3 * =======
4 *
5 * Workers manages either processes (in node) or threads (in a browser). The
6 * workers are intended to handle CPU-heavy tasks that block IO. This class is
7 * a little unusual in that it must use different interfaces whether in node or
8 * in the browser. In node, we use node's build-in child_process fork to create
9 * new workers we can communicate with. In the browser, we use web workers.
10 * Unfortunately, node and web browsers do not have a common interface for
11 * workers. There is a node module called webworker-threads for node that
12 * mimics the browser's web workers, but unfortunately it does not support
13 * require(), and thus isn't very useful in our case. Therefore we fall back to
14 * process forks.
15 *
16 * You probably don't need to use this class directly. Use Work, which will
17 * automatically spawn new workers if needed.
18 */
19'use strict'
20
21import { WorkersResult } from './workers-result'
22
23let globalWorkers
24
25class Workers {
26 constructor (
27 nativeWorkers = [],
28 lastid = 0,
29 incompconsteRes = [],
30 promisemap = new Map()
31 ) {
32 this.nativeWorkers = nativeWorkers
33 this.lastid = lastid
34 this.incompconsteRes = incompconsteRes
35 this.promisemap = promisemap
36 }
37
38 asyncObjectMethod (obj, methodname, args, id = this.lastid + 1) {
39 if (!args) {
40 throw new Error('must specify args')
41 }
42 const result = obj[methodname](...args)
43 const workersResult = new WorkersResult().fromResult(result, id)
44 return workersResult
45 }
46
47 static asyncObjectMethod (obj, methodname, args, id) {
48 if (!globalWorkers) {
49 globalWorkers = new Workers()
50 }
51 return globalWorkers.asyncObjectMethod(obj, methodname, args, id)
52 }
53
54 asyncClassMethod (classObj, methodname, args, id = this.lastid + 1) {
55 if (!args) {
56 throw new Error('must specify args')
57 }
58 const result = classObj[methodname](...args)
59 const workersResult = new WorkersResult().fromResult(result, id)
60 return workersResult
61 }
62
63 static asyncClassMethod (classObj, methodname, args, id) {
64 if (!globalWorkers) {
65 globalWorkers = new Workers()
66 }
67 return globalWorkers.asyncClassMethod(classObj, methodname, args, id)
68 }
69
70 static endGlobalWorkers () {
71 if (globalWorkers && !process.browser) {
72 globalWorkers = undefined
73 }
74 }
75}
76
77export { Workers }