JavaScript producer-consumer model

Because achieve node using a single-threaded way, so use this timer timer to achieve producer-consumer model to replace the thread 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             the else {
 24                  // meet production goals, dormant thread 
25                  SLEEP ();
 26 is              }
 27              productLock = to false ;
 28          }
 29      }
 30 }, 500 );
 31 is  
32  
33 is  var consumerTimer = the setInterval ( function () {
 34 is      IF ! ( productLock ) {
 35          IF ! ( productLock) {
 36              productLock = to 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);

Guess you like

Origin www.cnblogs.com/mikeCao/p/12214971.html