Search code examples
c++multithreadingboost-thread

C++ condition variable scope


I was working on a design and was trying to figure out how to use condition variables in multi threaded applications. My situation is like the case described below:

class MyClass1
{
  boost::mutex mut;
  boost::condition_variable var;

  public:

  void myfunc1()
  {
    boost::scoped_lock mylock(mut);

   //Wait untill notification is invoked
    var.wait(lock);

    //Continue processing after waking up
  }

  void wakeupClass1()
  {
    //Call notify to wake up only myfunc1
    var.notify_one();
  }
};

class MyClass2
{
  boost::mutex mut;
  boost::condition_variable var;

  public:

  void myfunc2()
  {
    boost::scoped_lock mylock(mut);

    //Wait untill notification is invoked
    var.wait(lock);

    //Continue processing after waking up
  }

  void wakeupClass2()
  {
    //Call notify to wake up only myfunc2
    var.notify_one();
  }
};

My question is when notifyone() is called in wakeupclass1(), will it wake up the condition variable in MyClass2 or will it be limited to waking up the thread within the class scope of Class1 where the first conditional variable was declared. in the code, You must note that the conditional variable in each class has exactly the same name. But my question is whether C++ language restricts conditional variable usage to within the scope where it is declared i.e. within the class. If this works, The advantage in the design in this piece of code is each Class MyClass1 and MyClass2 can run in seperate threads and when each class's corresponding wakeup function is called, only the thread running that particular class's myfunc will be executed which can be very useful in multithreaded applications.


Solution

  • Apart the fact that you declare a scoped_lock named mylock and then use lock (I assume you meant mylock again) there is another point: you ave different instances of the lock variable. When you notify on a variable what gets unlocked is a thread waiting on the same variable. A typical situation is one like this:

    template <class T>
    class shared_list
    {
    public:
      void pack(cont T &t)
      {
         boost::scoped_lock lock(mut) ;
         data.push_back(t) ;
         condition.notify_one() ;
      }
      T pop(void)
      {
         boost::scoped_lock lock(mut) ;
         do 
         {  condition.wait(lock) ;} while (data.empty() ;}
         T result = *data.begin() ;
         daa.pop_front() ;
         return result ;
      }
    private:
      std::list<T> data ;
      boost::mutex mut;
      boost::condition_variable var;
    } ;
    

    Here you can push and pop data to the list from different threads (and implement the typical producer-consumer scheme)