in reply to using parallel processing to concatenate a string, where order of concatenation doesn't matter
Try this. I've used a randomly variable 'work pause', as if this is constant, the threads will obviously finish in the same order as they started.
Update: Applied locks per ikegami's post below.
#! perl -slw use strict; use threads; use threads::shared; my $content : shared = ''; sub concatenate_parallel { my $letter = shift; sleep 1 + rand 2; ## Do stuff that takes time { lock $content; $content .= $letter; } } print scalar localtime; my @threads = map{ threads->create( \&concatenate_parallel, $_ ) } 'a' + .. 'c'; $_->join for @threads; print $content; print scalar localtime; __END__ c:\test>579015 Wed Oct 18 18:01:20 2006 cab Wed Oct 18 18:01:22 2006 c:\test>579015 Wed Oct 18 18:01:24 2006 bca Wed Oct 18 18:01:26 2006 c:\test>579015 Wed Oct 18 18:01:27 2006 abc Wed Oct 18 18:01:29 2006 c:\test>579015 Wed Oct 18 18:01:30 2006 abc Wed Oct 18 18:01:32 2006
If you don't like the shared buffer being passed to the threads through closure--it smacks of globals--then you could use this version that passes a reference to the shared buffer to the threads as an argument and dereferences it when appending:
#! perl -slw use strict; use threads; use threads::shared; sub concatenate_parallel { my( $contentRef, $letter ) = @_; sleep 1 + rand 2; ## Do stuff that takes time { lock $contentRef; $$contentRef .= $letter for 1 .. 1e4; } } my $content : shared = ''; my $contentRef = \$content; print scalar localtime; my @threads = map{ threads->create( \&concatenate_parallel, $contentRef, $_ ); } 'a' .. 'z'; $_->join for @threads; print $content; print scalar localtime; __END__ c:\test>579015 Thu Oct 19 00:33:11 2006 cbefghlmqsvwadijknoprtuxyz Thu Oct 19 00:33:13 2006
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: using parallel processing to concatenate a string, where order of concatenation doesn't matter
by ikegami (Patriarch) on Oct 18, 2006 at 18:58 UTC | |
by BrowserUk (Patriarch) on Oct 18, 2006 at 19:03 UTC | |
by ikegami (Patriarch) on Oct 18, 2006 at 19:32 UTC |