tormod has asked for the wisdom of the Perl Monks concerning the following question:
Update: Sollution/Workaround at bottom.
I have an application using threads that uses system calls. The main thread start up some worker threads and puts work on a queue that's dequeued in the worker threads. The worker threads puts the result on a queue that's dequeued in a non-blocking call in the main thread. The program hangs after a while and the problem seems to be a system call in the worker threads.
I've narrowed the problem down and provide an example that eventually will freeze when run on Windows. The application can run on Linux, but on Windows it hangs quite quick.
use strict; use threads; use Thread::Queue; my $PingQueue = Thread::Queue->new; my $PingResQueue = Thread::Queue->new; my $requestsinprocess = 0; my $ping = 'ping -c 1'; # Ping for Li +nux $ping = 'ping -n 1' if ( $^O eq 'MSWin32'); # Ping for Wi +ndows foreach my $i ( 0..7 ) { # Create some + threads my $pingthread = threads->new(\&Ping,$i)->detach; } while ( 1 ) { # Check for finished pings if ( $requestsinprocess > 0 ) { + # Check if there is anything on PingResQueue while ( defined ( my $pingres = $PingResQueue->dequeue_nb ) ) { + # with a non blocking dequeue of PingResQueue print "$pingres\n"; $requestsinprocess--; } } if ( $requestsinprocess == 0 ) { # Start a new round +with pings foreach ( 0..17 ) { $PingQueue->enqueue("127.0.0.1"); # Put ip on PingQueu +e, it's dequeued in &Ping() $requestsinprocess++; } } select( undef, undef, undef, 0.1 ); # Sleep a while } exit 0; sub Ping { my $id = shift; my $tolalping = 0; while (my $ip = $PingQueue->dequeue) { # Block here and w +ait for an ip on PingQueue my $pingres = `$ping $ip`; # Do a system call $PingResQueue->enqueue("$id " . $tolalping++); # Put something on + PingResQueue to be dequed in the main thread } }
Sollution/Workaround
Instead of using backticks I use open and put locks around the call to open.
$FHLocksemaphore->down; my $pid = open($chldout, "$command |"); $FHLocksemaphore->up; while ( defined ( my $buf = <$chldout> ) ) { $Result[@Result] = $buf; } close($chldout);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: System call in thread hangs threaded application on win32
by BrowserUk (Patriarch) on Feb 26, 2010 at 13:52 UTC | |
by tormod (Novice) on Feb 26, 2010 at 14:04 UTC | |
by BrowserUk (Patriarch) on Feb 26, 2010 at 14:49 UTC | |
by tormod (Novice) on Feb 26, 2010 at 16:44 UTC | |
by BrowserUk (Patriarch) on Feb 26, 2010 at 17:10 UTC | |
by cdarke (Prior) on Feb 26, 2010 at 15:03 UTC | |
|
Re: System call in thread hangs threaded application on win32
by Totzi (Initiate) on Feb 26, 2010 at 16:02 UTC |