Okay. Over the course of spawning 1000 threads, this version will use `1/16th (~13MB) of the memory required by my original version above. It substitutes a shared variable for the array of thread handles, and detaches the threads so they clean themselves up rather than sitting around consuming memory (~208MB) as in the original version.
The numbers will vary depending upon how many threads exist concurrently. If you are likely to be spawning anything like this number of threads, moving to a thread pool would be your best bet, though it is slightly more complex.
Without knowing what your program is actually doing, and it dynamic resource demands, it is quite likely that this version will also not be best for your application. Hence my /msg for further information. There is no one-size-fits-all solution.
#! perl -slw use strict; use threads; use threads::shared; $|=1; our $N ||= 1_000; my $threads :shared = 0; for my $i ( 1 .. $N ) { ## if the condition is true if( $i & 1 ) { ## every odd number matches ## Start a thread to run the sub ## Passing the number as an argument ## And saving the thread object, async( \&other, $i )->detach; } } ## Wait for all the threads to finish sleep 1 while $threads; printf "Check Memory"; <STDIN>; ## Done. exit; sub other{ { lock $threads; ++$threads; } my( $number ) = @_; print "Other( $number ) starting"; ## pretend we've doing something that takes a while... for( 1 .. rand 100 ) { print "Other( $number ) busy ..."; Win32::Sleep 100; } print "Other( $number ) finished"; { lock $threads; --$threads; } }
In reply to Re^4: create new task from main program
by BrowserUk
in thread create new task from main program
by benlaw
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |