JS實現經典生產者消費者模型

來源:互聯網
上載者:User

標籤:生產者消費者模型   nodejs   

由於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   : [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(將#更換為@)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.