C++ Thread, shared data

前端 未结 10 1854
悲&欢浪女
悲&欢浪女 2020-12-04 22:35

I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don\'t

10条回答
  •  粉色の甜心
    2020-12-04 23:01

    Here is an example that uses boost condition variables:

    bool _updated=false;
    boost::mutex _access;
    boost::condition _condition;
    
    bool updated()
    {
      return _updated;
    }
    
    void thread1()
    {
      boost::mutex::scoped_lock lock(_access);
      while (true)
      {
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        // note that the second parameter to timed_wait is a predicate function that is called - not the address of a variable to check
        if (_condition.timed_wait(lock, &updated, xt))
          updateScreen();
        doSomethingElse();
      }
    }
    
    void thread2()
    {
      while(true)
      {
        if (doSomething())
          _updated=true;
      }
    }
    

提交回复
热议问题