in reply to Re^2: Forking Multiple Regex's on a Single String (use threads)
in thread Forking Multiple Regex's on a Single String
As I mentioned above, if the threaded C-runtime your copy of perl is built against is any good, it will take care of serialising access to global resources (like STDOUT) for you. However, if in practice you find that the output from the threads is getting intermingled, then the following two additional lines to my code above should prevent that (with the caveat that I don't have a multi-cpu machine to test this on):
... my %motifs : shared; my $semaphore : shared; ################# Added. ... while ( ($pos = index( $sequence, $str, $pos)) >= 0 ) { lock $semaphore; ################################# Added. print join "\t", $chromosome, $pos, $motif; $pos += $len; }
There are several ways to approach limiting the number of concurrent threads. I would normally advocate using a pool of threads, but given the size of the data sets being loaded in each thread, discarding them after each use and spawning a new one is probably the safest way of ensuring most of the memory is returned to the heap for re-use.
Your revised code looks good, but I would suggest a couple of changes.
Something like this (untested) code:
my @waiting = @chromosomes; my %threads; my $max_threads = 10; ## Continue to join threads as the become joinable ## whilst there are still threads running while( @waiting or threads->list( threads::running ) ) { if( keys %threads < $max_threads ) { my $chr = pop @waiting; $threads{ $chr } = threads->new( \&threading_function, $chr ); } ## Do this regardless of whether it's time to start a new thread. foreach my $chr ( keys %threads ) { if( $threads{ $chr }->is_joinable ) { $threads{ $chr }->join; delete $threads{ $chr }; } } sleep 1; ## Prevent this thread consuming all spare cpu }
Don't get hung up on my changes to your formatting. When you're used to seeing things a certain way, it's easier to follow the logic when the code looks that way. I'm not advocating my preferences here.
|
---|