in reply to Re^11: Threads sharing global variable (disingenous)
in thread Threads sharing global variable

If you were running my posted code, you'd be getting 3 numbers on each "At printer ... " line.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
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". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.
  • Comment on Re^12: Threads sharing global variable (disingenous)

Replies are listed 'Best First'.
Re^13: Threads sharing global variable (disingenous)
by Anonymous Monk on Mar 10, 2016 at 13:48 UTC
    1156646.pl | egrep "printer 0 0" ... At printer 0 0 59 At printer 0 0 0 At printer 0 0 0 At printer 0 0 0 At printer 0 0 0 At printer 0 0 54 At printer 0 0 0 At printer 0 0 0 At printer 0 0 0 At printer 0 0 0 At printer 0 0 88 At printer 0 0 0 At printer 0 0 74 ...
    use threads; use threads::shared; use Thread::Queue; my $a :shared = 0; my $q = Thread::Queue->new(); sub set_positive { lock $a; while (1) { if ($a == 0) { $a = int(rand() * 100); $q->enqueue($a); # print "At set_positive: $a\n"; } else { cond_wait($a) } cond_broadcast($a); } } sub set_zero { lock $a; while (1) { if ($a > 0) { $a = 0; $q->enqueue($a); # print "At set_zero: $a\n"; } else { cond_wait($a) } cond_broadcast($a); } } sub printer { my ( $v_a, $v_b ); my $cnt = 100000; while ( 1 ) { ( $v_a, $v_b ) = $q->dequeue( 2 ); print "At printer $v_a $v_b ",$a, $/; # print "At printer $v_a $v_b\n"; exit unless --$cnt; } } threads->create( $_ ) for qw( set_positive set_zero printer ); $_->join() for threads->list;

      That code isn't my code. The lock()s are outside of the while loop, mine are inside.

      Once again, I'm not sure what point you are trying to make; but since you can't even get the distinction of the difference between my working code and ikegami's broken code, I've lost interest in continuing...


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      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". I knew I was on the right track :)
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Ok. ikegami made a correct statement about cond_wait in which the lock is re-obtained before cond_wait returns. This is documented in the threads::shared documentation. Ikegami did not lie.

        I ran your demonstration with the lock outside the while loop. The $cnt variable in the printer routine is for having the script exit at some point.