Boost logo

Boost Users :

Subject: Re: [Boost-users] wait/notify problem
From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2010-01-15 11:59:36


On Fri, Jan 15, 2010 at 4:09 AM, girish hilage <girish_hilage_at_[hidden]>wrote:

> Hi,
>
> when thread1 wants to listen for some event from thread2, it executes
> wait().
> when thread2 wants to inform about the event to thread1, it executes
> notify().
>
> The problem I am facing is :
> thread1 first executes wait().
> then thread2 executes notify().
>
> but notify() completes its execution even before thread1 actually
> starts waiting for the event and notify() is goes in vain and then thread1
> keeps on waiting infinitely.
>
>
> Regards,
> Girish
>
>
You need state external to the event. A variable like
   static int things_to_do = 0; // shared

   void thread1()
   {
      scoped_lock lock(mutex);

      while (!exit)
      {
         while (!things_to_do)
            cond.wait(mutex);

        do_things();
      }
   }

   void thread2()
   {
      {
        scoped_lock lock(mutex);
        add_thing_to_do();
        things_to_do++;
      }
     cond.notify();
   }

Tony



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