因為node使用單線程的方式實現,所以,在此使用定時器timer取代線程thread來實現生產者消費者模型。
1 var sigintCount = 0; 2 var productArray = []; 3 var productArrayLen = 0; 4 var productLock = false; 5 var PRODUCT_ARRAY_THRESHOLD = 10; 6
7 var sleep = function () { 8 clearInterval(producerTimer); 9 clearInterval(consumerTimer); 10 console.log('Production has been completed and the productArrayLen is:' + productArrayLen); 11 console.log('Thank you for use, Bye bye ~'); 12 } 13
14 var producerTimer = setInterval(function () { 15 if(!productLock) { 16 if(!productLock) { 17 productLock = true; 18 if(productArrayLen < PRODUCT_ARRAY_THRESHOLD) { 19 productArrayLen ++; 20 productArray.push('product'); 21 console.log('product:' + productArrayLen + ' producer.push'); 22 } 23 else{ 24 // 達到生產目標,休眠線程
25 sleep(); 26 } 27 productLock = false; 28 } 29 } 30 }, 500); 31
32
33 var consumerTimer = setInterval(function() { 34 if(!productLock) { 35 if(!productLock) { 36 productLock = true; 37 if(productArrayLen > 0) { 38 var product = productArray.shift(); 39 productArrayLen --; 40 console.log('product:' + productArrayLen + ' producer.pop'); 41 } 42 else{ 43 console.log('product:' + productArrayLen + ' producer.idle'); 44 } 45 productLock = false; 46 } 47 } 48 }, 1000);