Sorry. I shouldn't post just before leaving. You're right. There is still no architected way to find out how many detached threads are still running. So, you need to implement some counting mechanism yourself.
A simple shared scalar that you increment when the threads start and decrment when the threads end is simple and efficient.
#!/usr/bin/perl -w
use strict;
use threads;
use threads::shared;
my $running :shared = 0;
for (my $i = 0; $i < 50; $i++){
my $thr = threads->create( \&_run_thread, $i );
$thr->detach;
sleep 1;
}
sleep 1 while $running;
print "ok.\n";
sub _run_thread {
{ lock $running; ++$running; }
my ($id) = @_;
print "starting thread $id ...\n";
sleep 4;
print "exiting thread $id.\n";
{ lock $running; --$running; }
return;
}
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] |
What that comes down to getting the parent to know when a thread has finished.
You could use Thread::Queue, and each thread can enqueue its id when it's finished. The parent could wait on that queue or poll it.
Or you could poll threads->list(threads::joinable) for threads you can polish off by joining. You might do that before creating a new thread, I suppose.
| [reply] [d/l] [select] |
thanks. seems a bit odd, I don't see why it has to work like this. It ought to be trivial to run the script until all threads are ended, without clogging memory
In the end I just made a threadless version with a very simple scheduler, it took me about an hour to change it and it works perfectly on almost 0 resources
| [reply] |
I believe what's going on here is that each thread, once it has finished, has a "return" value in its hot little hands.
If you detach the thread, you've said you don't want the "return" value, so as soon as it's finished, the thread can tidy up after itself and leave the building.
Otherwise, until you join (or detach) the thread, it's sitting there, waiting patiently to give its final report, before it tidies up and leaves. (Kind of sad, really, given how much you care !)
| [reply] |