Based on Web Workers supported by all modern browsers.
TypeScript-ready.
Multithreading is simple
async function main() {
const args = [ 10, 20 ];
const result = await execAsync((a, b) => {
return a + b;
}, args);
console.log(result); // 30
}
// import function execAsync(func, args)
function testCase() {
let total = 0;
for(let i = 0; i < 99999999; ++i) {
total += Math.random() * 2;
}
return total;
}
async function test1() {
console.time('single thread');
testCase();
testCase();
testCase();
console.timeEnd('single thread');
}
async function test2() {
console.time('multi thread');
await Promise.all([
execAsync(testCase, []),
execAsync(testCase, []),
execAsync(testCase, [])
]);
console.timeEnd('multi thread');
}
Results
single thread: 3907.119140625ms
multi thread: 2017.375732421875ms
async function execAsync<ReturnT>(thread: (...args: any[]) => ReturnT, args: any[]): Promise<ReturnT>;
Only plain type values for arguments.
No access to variables in scope, only arguments.
No native functions or functions defined in other origin.
- Callback support
There is much complex library - threads.