JavaScript 生产者消费者模型

因为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);
posted @ 2020-01-19 17:39  Mike丶  阅读(1142)  评论(0编辑  收藏  举报