1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| class WorkerPool {
static instance; constructor(maxWorkers, workerScript) { if (WorkerPool.instance) { return WorkerPool.instance; }
console.log('创建线程池'); document.getElementById('task').value += `创建线程池\n`;
this.maxWorkers = maxWorkers; this.workerScript = workerScript; this.workers = []; this.taskQueue = []; this.idleWorkers = [];
this.initialize();
WorkerPool.instance = this; }
initialize() { for (let i = 0; i < this.maxWorkers; i++) { const worker = new Worker(this.workerScript); worker.onmessage = (event) => this.handleTaskComplete(worker, event); worker.onerror = (error) => console.error('Worker error:', error); this.workers.push(worker); this.idleWorkers.push(worker); } }
handleTaskComplete(worker, event) { console.log('Task completed:', event.data); document.getElementById('task').value += event.data + '\n';
this.idleWorkers.push(worker);
if (this.taskQueue.length > 0) { const { task, resolve, reject } = this.taskQueue.shift(); this.runTask(task, resolve, reject); } }
submitTask(task) { return new Promise((resolve, reject) => { if (this.idleWorkers.length > 0) { this.runTask(task, resolve, reject); } else { this.taskQueue.push({ task, resolve, reject }); } }); }
runTask(task, resolve, reject) { if (this.idleWorkers.length > 0) { const worker = this.idleWorkers.pop(); try { worker.postMessage(task); worker._resolve = resolve; worker._reject = reject; } catch (error) { reject(error); this.idleWorkers.push(worker); } } }
terminate() { this.workers.forEach((worker) => worker.terminate()); this.workers = []; this.idleWorkers = []; this.taskQueue = []; } }
const workerScript = ` self.onmessage = (event) => { const task = event.data;
console.log('Processing:', task);
// 模拟耗时任务 setTimeout(() => { const result = \`Processed: \${task}\`; self.postMessage(result); }, Math.random() * 2000 + 1000); }; `;
const blob = new Blob([workerScript], { type: 'application/javascript' }); const workerScriptUrl = URL.createObjectURL(blob);
const pool = new WorkerPool(6, workerScriptUrl);
for (let i = 0; i < 10; i++) { pool.submitTask(`Task ${i}`); }
window.addEventListener('beforeunload', () => { pool.terminate(); });
|