首页 > 代码库 > JS实现经典生产者消费者模型

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(石硕)的CSDN博客:blog.csdn.net/shishuo365  如有疑问请发邮件shishuo365#126.com(将#更换为@)