Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I need to write a perl program with two threads. Thread 1 should do read and write operation which is a time taking process. And Thread2 should keep on polling till thread1 complete its task. In case if thread1 fails (read or write fails) the program should exit (both the thread should exit). I have tried some thing like below

#! /usr/bin/perl use strict; use warnings; my $libPath; use threads; use threads::shared; my %share_threads; share (%share_threads); my $thread1 = threads->create(\&readWrite); my $thread2 = threads->create(\&isPollable); $thread1->join(); $thread2->join(); sub readWrite { # thread started $share_threads{threads->self->tid()} = 1; my $i=0; //Read and Write while ( $i<=10000) { print "==\n"; $i++; } # thread ended $share_threads{threads->self->tid()} = 0; } sub isPollable { print "Thread2 started\n"; # Polling while ( $share_threads{$thread1->tid()} ) { print "#"; } }

In case if the first thread exits, am getting an error thread1 exited abnormally. How to handle closing or exiting the threads properly. Thread2 should stop if the thread1 is exited? Any help would be highly appreciable.

Thanks.

Replies are listed 'Best First'.
Re: Two threaded program
by BrowserUk (Patriarch) on Oct 11, 2011 at 15:24 UTC

    You are creating a 3 thread process. The simplest way to do what you've described would be:

    use strict; use warnings; use threads; async{ open my $In, ...; open my $out, ...; while( <$in> ) { print $out; } }->join;

    And that's it. Of course it's not very useful as is, but then neither is what you posted.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Two threaded program
by zwon (Abbot) on Oct 11, 2011 at 14:44 UTC

    I don't see why you can't do this all in one thread, as tasks are not parallel, but here's a couple of notes. Instead of checking variable value in a loop, use cond_wait and cond_signal (see threads::shared). Wrap read/write loop into eval block, so you could catch any errors and still send signal to waiting thread to exit.

Re: Two threaded program
by thargas (Deacon) on Oct 11, 2011 at 18:29 UTC
    Seems to me that the problem described would be better suited to fork/wait rather than using threads at all. Of course it may be that the description of the problem has been simplified too far.