multithreading - Not all threads finishing, maybe due to not locking STDOUT -
i experimenting threads in perl. following code creates n threads , assigns same function them (which should execute in parallel).
twist: function prints something. means can't in parallel. fine since starting things them not threads seem finish. suppose due fact haven't locked std out , why conficts occur. may not reason. in case different ammount of threads not finishing each time.
if correct, how can lock stdout (i error when try use lock function) ?
if wrong, why threads not finishing , how can fix ?
the code:
use strict; use threads ('yield', 'stack_size' => 64*4096, 'exit' => 'threads_only', 'stringify'); use threads::shared; sub printtestmessage() { print "hello world\n"; } @t; push @t, threads->new(\&printtestmessage) 1..10;
i 10 times hello world, after program finishes different output:
perl exited active threads: 1 running , unjoined 9 finished , unjoined 0 running , detached perl exited active threads: 8 running , unjoined 2 finished , unjoined 0 running , detached perl exited active threads: 5 running , unjoined 5 finished , unjoined 0 running , detached
why haven't threads finished ? ( unjoined because never join them in code expected)
you have join threads, otherwise main thread (as in example) finish before child threads,
$_->join @t;
from perldoc threads
,
$thr->join()
this wait corresponding thread complete execution. when thread finishes, ->join() return return value(s) of entry point function.
Comments
Post a Comment