Here's a simple and reliable way of doing it:
#! perl -slw use strict; use threads; use threads::shared; use Thread::Queue; our $TIMEOUT //= 10; our $THREADS //= 16; our $PROCESSES //= 100; my $Q = new Thread::Queue; my $semSTDOUT :shared; sub tprint{ lock $semSTDOUT; print @_; } sub worker { my $tid = threads->tid; while( my $time = $Q->dequeue ) { my $pid :shared; my $th = async{ $pid = open my $pipe, '-|', qq[ perl -le"sleep $time; print \$\$, ' done'" ] or warn "Failed to start perl with time: $time" and nex +t; local $/; return <$pipe>; }; sleep 1; tprint "$tid: Started pid $pid for $time seconds"; my $t = 0; sleep 1 while kill( 0, $pid ) and ++$t < $TIMEOUT; if( kill( 0, $pid ) ) { tprint "$tid: $pid still running; killing"; kill 9, $pid; } else { tprint "$tid: $pid completed sucessfully"; } my $result = $th->join; tprint "$tid: pid $pid returned: '$result'"; ## Check result; } } my @workers = map async( \&worker ), 1 .. $THREADS; $Q->enqueue( map int( rand 2 * $TIMEOUT ), 1 .. $PROCESSES ); $Q->enqueue( (undef) x $THREADS ); $_->join for @workers; __END__ [23:21:02.98] c:\test>857569 -THREADS=4 -PROCESSES=10 -TIMEOUT=10 1: Started pid 4032 for 2 seconds 4: Started pid 3848 for 15 seconds 2: Started pid 3436 for 17 seconds 3: Started pid 2392 for 14 seconds 1: 4032 completed sucessfully 1: pid 4032 returned: '4032 done ' 1: Started pid 3640 for 11 seconds 4: 3848 still running; killing 4: pid 3848 returned: '' 2: 3436 still running; killing 2: pid 3436 returned: '' 3: 2392 still running; killing 3: pid 2392 returned: '' 4: Started pid 2872 for 7 seconds 3: Started pid 3604 for 3 seconds 1: 3640 still running; killing 1: pid 3640 returned: '' 3: 3604 completed sucessfully 3: pid 3604 returned: '3604 done ' 1: Started pid 1156 for 6 seconds 3: Started pid 4452 for 3 seconds 4: 2872 completed sucessfully 4: pid 2872 returned: '2872 done ' 3: 4452 completed sucessfully 3: pid 4452 returned: '4452 done ' 1: 1156 completed sucessfully 1: pid 1156 returned: '1156 done '
In reply to Re: Handling badly behaved system calls in threads
by BrowserUk
in thread Handling badly behaved system calls in threads
by kennethk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |