ワーカスレッドを安全に終了させるまで待機
Posted feedbacks - JavaScript
さらに Rhino で。
1 2 3 4 5 6 7 8 9 | (function doukaku116(nThread){
var out = new java.util.concurrent.ArrayBlockingQueue(nThread * 2);
for(var i = nThread; i--;) spawn(function(secs){
out.put('#start '+ (secs = Math.random() * 11 + 5 | 0));
java.lang.Thread.sleep(secs * 1000);
out.put('#stop '+ secs);
});
for(i = nThread * 2; i--;) print(out.take());
})(5);
|
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>
see: InfoQ: JavaScriptへのマルチスレッド・プログラミングの導入
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.");
});
|




todogzm
#4822()
Rating4/4=1.00
スレッドプールに複数のワーカスレッドが待機しており、メインスレッドはいつでもワーカスレッドに仕事を渡せるような状態になっているとします。
さて、メインスレッドからスレッドプールにいくつか仕事を与え、メインスレッドは与えた仕事すべてが終了するまで待機し、次の処理に行ってはいけない、というようなコードを書いてください。 #現実に書く機会が多そうなコードですね…。
ここでの仕事の内容は、適当に5秒から15秒の間スレッドをスリープする、というもので結構です。 また、ワーカスレッドのスレッドプール自体の使用を終了するか、または残して再利用するかは問いません。できればコメントにスレッドプールを残したかどうかを書いてください。
[ reply ]