|
Boost Users : |
From: Fabian Sturm (f_at_[hidden])
Date: 2007-11-23 14:05:26
Hi!
Thanks for the replies! I didn't expect so many!
So it seems that the preferred way to do it is using three shared
variables. The mutex the condition and a bool, which was the same I was
thinking about. Therefore my question for a solution with less shared
resoures. Since the FAQ states there is a solution with only a mutex and
a condition variable.
Anyways its good to know that the given examples are common practice.
Thanks again.
Fabian
Am Donnerstag, den 22.11.2007, 08:48 -0500 schrieb Steve Byan:
> On Nov 21, 2007, at 5:25 PM, Fabian Sturm wrote:
>
> > My problem is, that I have two threads A and B and thread A needs some
> > information that B will calculate at runtime. Therefore I need some
> > kind
> > of synchronization.
> >
> > So my first attempt was to use a mutex and a condition variable:
> >
> > Thread A:
> >
> > boost::thread::mutex::scoped_lock lock ( mMutex );
> > mConditionVar.wait ( lock );
> >
> > Thread B:
> >
> > mConditionVar.notify_one ();
> >
> > This works nice as long as thread A already started waiting on the
> > condition before thread B finished providing it. Otherwise the notify
> > will be lost.
>
> You need to create a shared condition variable, set by thread B and
> read by thread A.
> Thread A has to wait on the condition variable in a loop, like this:
>
> shared variable:
> bool theCondition = false;
>
> Thread A:
>
> {
> boost::thread::mutex::scoped_lock lock ( mMutex );
> while (!theCondition) {
> mConditionVar.wait ( lock );
> }
> }
>
> Thread B:
>
> {
> boost::thread::mutex::scoped_lock lock ( mMutex );
> theCondition = true;
> mConditionVar.notify_one ();
> }
>
>
>
> I suggest you take a look at a tutorial text on POSIX threads
> (pthreads); it should explain the use of mutexes and condition
> variables more thoroughly.
>
> Regards,
> -Steve
>
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net