Comment detail

ワーカスレッドを安全に終了させるまで待機 (Nested Flatten)

Pure-JavaScript(?)でProducer-Consumerパターンを組んでみました。 Concurrent.Threadライブラリを使用しています。なお、スレッドプール停止後に再開することはできません。

<html><body> <script type="text/javascript" src="Concurrent.Thread.ScriptExecuter+Http.js"></script> <script type="text/javascript" src="producer_consumer.js"></script> </body></html>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Concurrent.Thread.create(function() {
  var pool = {stop : false, queue : [], threads : [], waitSet : [], 
      puts : function puts(s) { document.body.innerHTML += s + "<br>"; }};
  pool.worker = Concurrent.Thread.compile(function(){
    var job;
    while (!this.stop) {
      job = this.queue.shift();
      if(job) {
        this.puts("sleep " + job + " seconds.");
        Concurrent.Thread.sleep(job * 1000);
      } else {
        try {
          waitSet.push(Concurrent.Thread.self());
          Concurrent.Thread.stop();
        } catch(e) {
          if(e instanceof Concurrent.Thread.KillException)  throw e;
        }
      }
    }
    this.puts("stop");
  });

  pool.producer = Concurrent.Thread.compile(function(){
    var job;
    while (!this.stop) {
      this.queue.push(Math.floor(Math.random() * 10));
      Concurrent.Thread.sleep(Math.floor(Math.random() * 1000));
      var cons = this.waitSet.pop();
      if(cons) cons.notify("wake up!");
    }
    this.puts("producer stop");
  });

  for(var i=0; i<10; i++) pool.threads[i] = pool.worker.async(pool);

  pool.threads.push(pool.producer.async(pool));

  setTimeout(function() { pool.stop = true; } , 10*1000);

  for(var i=0; i<5; i++) pool.threads[i].join();

  pool.puts("All threads is stoped.");
});

修正漏れ。

1
2
3
4
@@ -40,3 +40,3 @@

-  for(var i=0; i<pool.threads.length; i++) pool.threads[i].join();
+  for(var i=0; i<5; i++) pool.threads[i].join();

Index

Feed

Other

Link

Pathtraq

loading...