最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

javaScript中worker實(shí)現(xiàn)線程池的示例代碼

 更新時(shí)間:2025年06月20日 11:18:15   作者:不穿鎧甲的穿山甲  
本文主要介紹了javaScript中worker實(shí)現(xiàn)線程池,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

目錄結(jié)構(gòu):

在這里插入圖片描述

Lock

class Lock {
	static locks = {};
	static getInstance(key = ""){
		let instance = this.locks[key];
		if(null == instance){
			instance = new Lock();
			this.locks[key] = instance;
		}
		
		return instance;
	}
	
	constructor(){
		const sab = new SharedArrayBuffer(4);
		this._arr = new Int32Array(sab);
		Atomics.store(this._arr, 0, 0);
	}
	
	acquireLock() {
		let acquired = false;
		while (!acquired) {
			const expected = 0;
			const actual = Atomics.compareExchange(this._arr, 0, expected, 1);
			acquired = (actual === expected);
			if(acquired){
			//	console.log('Lock acquired in worker thread');
				return;
			}
			//console.log('Lock acquired in worker thread, wait');
			Atomics.wait(this._arr, 0);
			//console.log('Lock acquired in worker thread',"被喚醒");
		}
	}
	
	releaseLock() {
	//	console.log('Lock released in worker thread');
		Atomics.store(this._arr, 0, 0);
		Atomics.notify(this._arr, 0);
	}
	
}


module.exports = Lock;

BlockingQueue

let Lock = require('./Lock.js');

class BlockingQueue{
	constructor(key = ""){
		this._data = [];
		this._lock = Lock.getInstance(key);
	}
	
	getSize(){
		try{
			this._lock.acquireLock();
			return this._data.length;
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	offer(message){
		try{
			this._lock.acquireLock();
			this._data.push(message);
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	pop(){
		try{
			this._lock.acquireLock();
			return this._data.pop();
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	popList(count = 1){
		try{
			this._lock.acquireLock();
			let arr = [];
			count = count > this._data.length ? this._data.length : count;
			for(let index = 0; index < count; index ++){
				arr.push(this._data.pop());
			}
			return arr;
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	remove(arr){
		try{
			this._lock.acquireLock();
			this._data = this._data.filter(item => !arr.includes(item));
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	remove(item){
		try{
			this._lock.acquireLock();
			this._data = this._data.filter(em => !em == item);
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
	getArr(){
		try{
			this._lock.acquireLock();
			return this._data;
		}catch(e){
			console.error(e);
		}finally{
			this._lock.releaseLock();
		}
	}
	
}

module.exports = BlockingQueue;

Message

class Message{
	constructor(data){
		this._data = data;
	}
	
	getData(){
		return this._data;
	}

}

module.exports = Message;

線程實(shí)現(xiàn)

worker.js

const {
	parentPort,
	threadId
} = require('worker_threads');

parentPort.on('message', (msg) => {
	let data = msg.data;
	let fun = eval(msg.fun);
	fun(data);
	console.log("threadId=",threadId, " data=", msg)
	//parentPort.postMessage(msg);
});

Thread

const {
	Worker
} = require('worker_threads');
var path = require('path')
let workerJsPath = path.resolve(__dirname +'/worker.js')

class Thread {
	
	constructor(runnable, name = "") {
		this._name = name;
		this._target = runnable;
		this._interrupted = false;
	}

	run() {
		this._target.run()
	}

	start() {
		this._initForkThread();
	}
	
	stop(){
		this._worker.terminate();
	}
	
	_initForkThread(){
		this._worker = new Worker(workerJsPath);
		// this._worker.on('message', (msg) => {
		// 	this._target.data = msg;
		// 	this._target.status = "done";
		// 	console.log("收到回復(fù)", msg)
		// });
		
		this._worker.on('exit', (msg) => {
			this._interrupted = true;
			console.log("線程中斷")
		});
		
	}
	
	isInterrupted(){
		return this._interrupted;
	}
	
	getName(){
		return this._name;
	}
	
	postMessage(message){
		this._worker.postMessage({
			fun: `${this._target}`,
			data: message.data
		});
	}

}

module.exports = Thread;

TaskThread

class TaskThread{
	
	constructor(thread, queue){
		this._thread = thread;
		this._queue = queue;
	}
	
	start(){
		this._thread.start();
		try{
			let start = performance.now();
			let interval = setInterval(() => {
				if(!this.isInterrupted()){
					let message = this._queue.pop();
					if(null == message){
						return;
					}
					this._thread.postMessage(message);
				}else{
					clearInterval(interval);
				}
			}, 500);

		}catch(e){
			console.error("錯(cuò)誤信息",e);
		}
	}
	
	isInterrupted(){
		return this._thread.isInterrupted();
	}
}

module.exports = TaskThread;

ThreadPool

let Thread = require("./Thread.js")
let BlockingQueue = require("./BlockingQueue.js")
let TaskThread = require("./TaskThread.js")

class ThreadPool{
	constructor(threadCount = 4){
		this._count = threadCount;
		this._queue = new BlockingQueue("queue"); 
		this._threads = new BlockingQueue("thread")
		setInterval(() => {
			if(0 == this._queue.getSize()){
				return;
			}
			//移除無(wú)效線程
			let removeThreads = this._threads.getArr().map(thread => thread.isInterrupted());
			this._threads.remove(removeThreads);
			
			// //檢驗(yàn)線程數(shù)
			let activeThreadCount = this._threads.getSize();
			if(activeThreadCount < this._count && this._queue.getSize() > 0){
				this.createThread(this._count - activeThreadCount);
			}
			
		}, 10);
	}
	
	createThread(count){
		for(let index = 0; index < count; index ++ ){
			let thread = new Thread((m) => {
				console.log(m)
			}, "fork_task_" + index);
			
			let taskThread = new TaskThread(thread, this._queue);
			this._threads.offer(taskThread);
			taskThread.start();
		}
	}
	
	addTask(message){
		this._queue.offer(message);
	}
}

module.exports = ThreadPool;

測(cè)試用例:
test.js

let ThreadPool = require("./ThreadPool.js")

let threadPool = new ThreadPool();

threadPool.addTask({
	data: "99999"
})

threadPool.addTask({
	data: "88888"
})

threadPool.addTask({
	data: "77777"
})

運(yùn)行test.js

node test.js

在這里插入圖片描述

到此這篇關(guān)于javaScript中worker實(shí)現(xiàn)線程池的文章就介紹到這了,更多相關(guān)javaScript worker線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

梅河口市| 平江县| 舟山市| 开阳县| 永吉县| 荆门市| 西林县| 丹寨县| 如东县| 宁远县| 分宜县| 思茅市| 清流县| 山丹县| 桃源县| 双江| 延庆县| 方城县| 营山县| 正安县| 陇西县| 天镇县| 扎兰屯市| 合肥市| 怀远县| 邯郸市| 台北县| 方正县| 鄂温| 碌曲县| 福鼎市| 灯塔市| 马山县| 大理市| 昔阳县| 宕昌县| 资中县| 抚顺县| 蒙自县| 米脂县| 历史|