test ts
This commit is contained in:
63
src/thread/thread.ts
Normal file
63
src/thread/thread.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Worker, isMainThread, MessageChannel, MessagePort } from 'worker_threads';
|
||||
import path from 'path';
|
||||
|
||||
const __filename = import.meta.url;
|
||||
const __dirname = path.dirname(__filename);
|
||||
const numThreads = 4;
|
||||
const workers: Worker[] = [];
|
||||
console.log('dirname',__dirname);
|
||||
for (let i = 0; i < numThreads; i++) {
|
||||
const worker = new Worker(path.resolve( 'worker.mjs'));
|
||||
workers.push(worker);
|
||||
}
|
||||
|
||||
const ports: MessagePort[] = [];
|
||||
for (let i = 0; i < numThreads + 1; i++) {
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
ports.push(port1);
|
||||
port1.on('message', (message) => console.log('received', message));
|
||||
// You can use port2 to communicate with the worker or another part of your application
|
||||
}
|
||||
|
||||
ports[0].on('message', (data) => {
|
||||
console.log('主线程收到消息:', data);
|
||||
});
|
||||
|
||||
for (let i = 1; i < numThreads + 1; i++) {
|
||||
ports[i].on('message', (data) => {
|
||||
const result = data;
|
||||
console.log(`子线程${i - 1}计算结果: ${result}`);
|
||||
});
|
||||
}
|
||||
|
||||
const total = 1000;
|
||||
const numbersPerThread = Math.ceil(total / numThreads);
|
||||
|
||||
for (let i = 0; i < numThreads; i++) {
|
||||
const start = i * numbersPerThread + 1;
|
||||
const end = (i + 1) * numbersPerThread;
|
||||
workers[i].postMessage({ start, end });
|
||||
}
|
||||
|
||||
if (!isMainThread) {
|
||||
self.onmessage = ({ data }) => {
|
||||
const { start, end } = data;
|
||||
let sum = 0;
|
||||
for (let i = start; i <= end; i++) {
|
||||
sum += i;
|
||||
}
|
||||
ports[0].postMessage(sum);
|
||||
};
|
||||
}
|
||||
|
||||
let totalSum = 0;
|
||||
ports.forEach((port, index) => {
|
||||
if (index === 0) return;
|
||||
port.on('message', (data) => {
|
||||
totalSum += data;
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
console.log(`所有子线程计算完成,总和为: ${totalSum}`);
|
||||
}, 1000);
|
||||
9
src/thread/worker.js
Normal file
9
src/thread/worker.js
Normal file
@@ -0,0 +1,9 @@
|
||||
const { parentPort } = require('worker_threads');
|
||||
|
||||
parentPort.on('message', ({ start, end }) => {
|
||||
let sum = 0;
|
||||
for (let i = start; i <= end; i++) {
|
||||
sum += i;
|
||||
}
|
||||
parentPort.postMessage(sum);
|
||||
});
|
||||
Reference in New Issue
Block a user