in reply to How to forcefully destroy a thread
$threads->join will wait for the thread to finish and then rejoin the parent. So you will have to signal the thread somehow, to tell it to return early. So broadcast some variable, and have the thread periodically test it, and if there, the thread will immediately return. Here is some code posted awhile back by another monk which demonstrates the idea.
or you can work up your own method. Just use the cond_broadcast to share variables between threads. A super simple demo:#!/usr/bin/perl -w use threads; use threads::shared; my $status : shared; my $thr_work = threads->create( sub { # do some work. lock $status; return if $status; $status = "done"; cond_signal $status; return @whatever; } ); threads->create( sub { sleep 300; lock $status; return if $status; $status = "timed_out"; cond_signal $status; } )->detach; { lock $status; cond_wait $status until $status; if ( $status eq "done" ) { my @results = $thr_work->join; # process @results. } else { print "Timed out\n"; $thr_work->detatch; } }
#!/usr/bin/perl use threads; use threads::shared; use strict; our $a:shared = 1; print "main start->$a\n"; threads->create(\&display); threads->create(\&display1); print "hit enter to finish\n"; <STDIN>; #pauses for keypress print "main done-> $a\n"; sub display { our $a = 2; $a++; print "from t1->$a\n"; } sub display1 { our $a = 99; print "front2->$a\n"; $a++; lock $a; cond_broadcast($a); }
|
|---|