- 前言:我们在学习 js 的过程中, 或多或少地都会听说过 “js是单线程的” 这句话。诚然,对于 js 本身来说,确实是单线程的,但是,js 的运行时已经给出了并发的解决方案。下面,就让我们感受一下,js 是如何实现多线程的。
Browser
// main.js
const one = new Worker('./one.js')
const two = new Worker('./two.js')
one.postMessage('我是主线程')
two.postMessage('我是主线程')
function receiveMessage(e) {
const { data } = e
const { source, res } = data
console.log(`我是${source}发来的信息,计算结果是${res}`);
}
one.onmessage = receiveMessage
two.onmessage = receiveMessage
// one.js
self.onmessage = (e) => {
const { data } = e
console.log(data);
const arr = new Array(10000).fill(1)
let s = 0
for (let i of arr) {
s += i
}
self.postMessage({
source: 'one',
res: s
})
}
// two.js
self.onmessage = (e) => {
const { data } = e
console.log(data);
const arr = new Array(10000).fill(1)
let s = 0
for (let i of arr) {
s += i
}
self.postMessage({
source: 'two',
res: s
})
}

Node
// main.js
const { Worker } = require('node:worker_threads')
const path = require('path')
const one = new Worker(path.join(__dirname, './one.js'), { workerData: 'Hello, world!' })
const two = new Worker(path.join(__dirname, './two.js'), {num: 2})
one.postMessage('主线程的消息')
two.postMessage('主线程的消息')
one.on('message', data => {
console.log('one 发送来的消息', data)
})
two.on('message', data => {
console.log('two 发送来的消息', data)
})
// one.js
const {
parentPort, workerData
} = require('node:worker_threads');
nmessage = (e) => {
const { data } = e
console.log(data);
}
parentPort.postMessage(workerData)
// two.js
const {
parentPort,workerData
} = require('node:worker_threads');
onmessage = (e) => {
const { data } = e
console.log(data);
}
parentPort.postMessage('我是two的信息', workerData)

兼容
// master.js
import { spawn, Thread, Worker } from "threads"
const auth = await spawn(new Worker("./workers/auth"))
const hashed = await auth.hashPassword("Super secret password", "1234")
console.log("Hashed password:", hashed)
await Thread.terminate(auth)
// workers/auth.js
import sha256 from "js-sha256"
import { expose } from "threads/worker"
expose({
hashPassword(password, salt) {
return sha256(password + salt)
}
})
小结
- 在日常开发中,如果遇到 大数据计算 或者 处理并发任务 的时候,不妨尝试一下 js 的并发方案。也许会有很大的收益。
- 也期待有相关经验的小伙伴,在评论区给出你的分享。