Boost logo

Boost :

From: Scott McCaskill (scott_at_[hidden])
Date: 2001-08-13 15:03:34


----- Original Message -----
From: "Peter Dimov" <pdimov_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Monday, August 13, 2001 2:36 PM
Subject: Re: [boost] Re: Threads docs updated in CVS

> From: "Alexander Terekhov" <terekhov_at_[hidden]>
>
> > > Yep, one queue per thread. Just like the original example - one CV per
> > > thread - unless I misinterpreted it.
> >
> > how about one mutex/CV *per queue* with multiple threads..
>
> What is the scenario? I can see the code and I think I understand it, but
> what is it supposed to do, and is this a common example? One thing that's
> not apparent from the code is whether notifyThread() is supposed to be
> "thread-safe" as well, i.e. are multiple threads allowed to concurrently
> call notifyThread.
>

The scenario here is that you have one or more threads issuing commands to
one or more worker threads who receive the commands and act accordingly. So
yes, multiple threads may call notifyThread() concurrently. I think this
may be one of the most common examples of the uses of CVs.

> It's possible to move the wakeup event into the queue as well; likeiwse,
in
> the cv-based example, we can move the mutex and the cv into the queue:
>
> void threadfunc()
> {
> for(;;)
> {
> int m;
>
> while(q.pop(m)) // blocks
> {
> if(m & 1) do_something_a();
> if(m & 2) do_something_b();
> if(m & 4) do_something_c();
> }
> }
> }
>
> void notifyThread(bool a, bool b, bool c)
> {
> q.push(a + 2 * b + 4 * c);
> }
>
> But this doesn't handle termination.
>

bool done = false;

void threadfunc()
{
  for(;;)
  {
    int command;
    {
      mutex::scoped_lock lock( m );
      while(q.empty() && !done)
        cv.wait( lock );
      if ( done ) break;
      command = q.pop();
    }
    if(command & 1) do_something_a();
    if(command & 2) do_something_b();
    if(command & 4) do_something_c();
  }
}

void tellThreadsToQuit()
{
  { mutex::scoped_lock lock( m ); done = true; }
  cv.notify_all();
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk