前端 Worker 池与任务调度实践概述多 Worker 并行处理重任务,主线程仅负责调度与交互,避免长任务阻塞。Worker 池实现(示意)class WorkerPool {
private workers: Worker[] = []
private queue: Array<{ data: any; priority: number; resolve: (v: any) => void }> = []
constructor(size: number, script: string) {
for (let i = 0; i < size; i++) this.workers.push(new Worker(script, { type: 'module' }))
}
submit(data: any, priority = 0) {
return new Promise((resolve) => {
this.queue.push({ data, priority, resolve })
this.queue.sort((a, b) => b.priority - a.priority)
this.dispatch()
})
}
private dispatch() {
const idle = this.workers.pop()
const task = this.queue.shift()
if (!idle || !task) return
idle.onmessage = (e) => { task.resolve(e.data); this.workers.push(idle); this.dispatch() }
idle.postMessage(task.data)
}
}
MessageChannel 协同const channel = new MessageChannel()
channel.port1.onmessage = (e) => console.log('result', e.data)
worker.postMessage({ task: 'process' }, [channel.port2])
技术参数与验证INP 改善;重任务吞吐提升;主线程帧率稳定。注意事项任务大小粒度控制;避免过度线程化;与优先级策略协同。---发布信息:已发布 · 技术验证 · 阅读 36 分钟 · CC BY-SA 4.0

发表评论 取消回复