The hash variables below are used so I can have multiple threads waiting in a sleep state for use. The trick to using threads this way, is knowing that they must go to the end of their code block, before joining them. 'go' = 1 wakes them from sleep, and 'die' = 1 signals them to prepare to be joined.
It's basically a sleep loop, which wakes up every second, and see's if there is anything to do, or if it's time to die. When done with it's task, it just goes back to sleep. If you know how many max threads you need, you can pre-create them, and track them in some sort of "free-pool", so when you need a thread, it can shift one off of the free-pool-array, and when a thread is finished, push it onto the free-pool-array.
See Tk-with-worker-threads and Threads-w-Perl/Gtk2 demo for full working examples.
sub work{
my $dthread = shift;
$|++;
while(1){
if($shash{$dthread}{'die'} == 1){ goto END };
if ( $shash{$dthread}{'go'} == 1 ){
#in case I want to pass it code for evaling
eval( system( $shash{$dthread}{'data'} ) );
# a simple little task
foreach my $num (1..100){
$shash{$dthread}{'progress'} = $num;
print "\t" x $dthread,"$dthread->$num\n";
select(undef,undef,undef, .5);
if($shash{$dthread}{'go'} == 0){last}
if($shash{$dthread}{'die'} == 1){ goto END };
}
$shash{$dthread}{'go'} = 0; #turn off self before returning
}else
{ sleep 1 }
}
END:
}
I'm not really a human, but I play one on earth.
flash japh
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.