JS实现经典生产者消费者模型

本文介绍如何利用 Node.js 的单线程特性,通过定时器替代线程来构建生产者消费者模型,包括代码示例和关键流程解析。
因为node使用单线程的方式实现,所以,在此使用定时器timer取代线程thread来实现生产者消费者模型。

代码例如以下:

var sigintCount = 0;
var productArray = [];
var productArrayLen = 0;
var productLock = false;
var PRODUCT_ARRAY_THRESHOLD = 10;

var producerTimer = setInterval(function () {
		if (!productLock) {
			if (!productLock) {
				productLock = true;

				if (productArrayLen < PRODUCT_ARRAY_THRESHOLD) {
					productArray.push('product');
					productArrayLen++;
					console.log('product:' + productArrayLen + '   producer.push');
				} else {
					console.log('product:' + productArrayLen + '   producer.idle');
				}

				productLock = false;
			}
		}
	}, 500);

var consumerTimer = setInterval(function () {
		if (!productLock) {
			if (!productLock) {
				productLock = true;

				if (productArrayLen) {
					var product = productArray.shift();
					productArrayLen--;
					console.log('product:' + productArrayLen + '   consumer.pop');
				} else {
					console.log('product:' + productArrayLen + '   consumer.idle');
				}

				productLock = false;
			}
		}
	}, 1000);

function readme() {
	console.log('==================================================');
	console.log('Auther  : shishuo');
	console.log('Date    : 2014-07-05');
	console.log('Blog    : http://www.hz601.org/heaven');
	console.log('Email   : shishuo365@126.com');
	console.log('License : GNU GPL v3');
	console.log('==================================================');
}

readme();

process.stdin.resume();
process.on('SIGINT', function () {
	sigintCount++;
	if (sigintCount > 1) {
		process.exit();
	} else {
		clearInterval(producerTimer);
		clearInterval(consumerTimer);
		console.log('Press two times Control-C to exit.');
	}
});

process.on('exit', function () {
	console.log('Thank you for use. Bye bye~');
});

欢迎交流~


转载请注明来自Master.R(石硕)的优快云博客:blog.youkuaiyun.com/shishuo365  如有疑问请发邮件shishuo365#126.com(将#更换为@)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值