I am trying to figure out issue with thread application.Basically i want a thread which sends data to pipeline and other thread gets data from pipeline and consume it. Issue is below code works fine :
use Thread::Queue; use threads; my $q = Thread::Queue->new(); # A new empty queue print "$q\n"; my $command = "ls -la"; print ("sending command...\n"); $q->enqueue($command); #sleep(60); $command = "pwd"; print ("sending command...\n"); $q->enqueue($command); #sleep(60); $q->end(); # Worker threads my $thr = threads->create(sub { print "running thread : $q\n"; while ((my $item = $q->dequeue())) { print "Running Command : $item \n"; my $result = `$item 2>&1`; print "Result of $item : $result \n"; } } ) ; # terminate. $thr->join();
The below code is similar to above one excepts use a function to send data and call that function in another thread but it doesn't work:
#!/usr/bin/perl use Thread::Queue; use threads; use threads::shared; my $q ; share($q); $q = Thread::Queue->new(); my $thr1 = threads->create(sub { my ($q) = @_; print "Running Thread1 : $q\n"; my $command = "ls -la"; print ("sending command...\n"); $q->enqueue($command); #sleep(60); $command = "pwd"; print ("sending command...\n"); $q->enqueue($command); #sleep(60); $q->end(); } , $q) ; # Worker threads my $thr2 = threads->create(sub { my ($q) = @_; print "running thread2 : $q\n"; while ((my $item = $q->dequeue())) { print "Running Command : $item \n"; my $result = `$item 2>&1`; print "Result of $item : $result \n"; } } ,$q) ; $thr1->join(); $thr2->join(); print "Done\n";

In reply to Perl thread issue by gurjit

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.