JS实现经典生产者消费者模型
代码如下:
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 : [email protected]'); 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(将#更换为@)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。