in reply to need a thread to wait until a buffer is full.

Something like this?

#! perl -slw use strict; use threads; use threads::shared; use Thread::Queue; $|++; sub filler { my( $Q ) = @_; while( my $ref = $Q->dequeue ) { lock $$ref; $$ref .= 'X'x10 while sleep 1 and length $$ref < 30; cond_signal $$ref; } } my $Q = new Thread::Queue; my $buffer :shared; my $filler = threads->create( \&filler, $Q ); for( 1 .. 5 ) { lock $buffer; $Q->enqueue( \$buffer ); cond_wait( $buffer ); print $buffer; $buffer = ''; } $Q->enqueue( undef ); ## kill thread $filler->join;

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.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: need a thread to wait until a buffer is full.
by archfool (Monk) on Jul 25, 2007 at 02:42 UTC
    The things you put in a Thread::Queue don't need to be shared. Just the Thread::Queue itself.
      he things you put in a Thread::Queue don't need to be shared. Just the Thread::Queue itself.

      They do if you want access them from more than one thread. Note that I am passing a reference to the shared buffer via the Queue, not the buffer itself.

      If you can see a better way of coding this, please post your code.


      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.
        The buffer contains raw binary data that can be anything, it is directly read from the hd, the other thread will read a block from the hd and put it into the buffer. I know that lock goes away after the scope {}. my problem is how do I ensure the thread that fills the buffer locks it before the thread that created it checks it. I do not want my thread that uses the buffer to lock it so that it can check if it is filled, then have the thing that fills it sit there and wait since the thread that uses it has the lock.... essentially my question is this: If I use lock in a loop, then when the loop goes to the next iteration is that going out of scope and releasing the lock, or is it holding the lock since it is one loop?

        --------------------------------------

        I would rather take 30 minutes to re-invent the wheel then take 30 days to learn how to use someone else's. Before pestering me about my re-invention prepare to defend yourself with a way of learning how to use the wheel in less time than it takes for me to make one, one that I might add is specialized to my specific task!