【问题标题】:Boost mutex order提升互斥顺序
【发布时间】:2011-01-17 13:41:48
【问题描述】:

所以有简单的类

class mySafeData
{
public:
  mySafeData() : myData(0)
  {
  }

void Set(int i) 
  {
    boost::mutex::scoped_lock lock(myMutex);
    myData = i; // set the data
    ++stateCounter;  // some int to track state chages
    myCondvar.notify_all(); // notify all readers
  }

  void Get( int& i)
  {
    boost::mutex::scoped_lock lock(myMutex);
    // copy the current state
    int cState = stateCounter;
    // waits for a notification and change of state
    while (stateCounter == cState)
      myCondvar.wait( lock );
  }
 private:
   int myData;
   int stateCounter;
   boost::mutex myMutex;
};

无限循环中的线程数组调用每个函数

 Get()
 Set()
 Get()
 Get()
 Get()

他们是否总是以相同的顺序调用函数,并且每个圆圈只调用一次(我的意思是所有提升线程每次都以相同的顺序运行,以便每个线程在一个 Set( ))?

【问题讨论】:

    标签: c++ multithreading boost locking


    【解决方案1】:

    没有。您永远不能对线程的服务顺序做出任何假设。这与 boost 无关,它是多道程序的基础。

    【讨论】:

      【解决方案2】:

      线程应该按照它们到达scoped_lock 构造函数的顺序获取锁(我认为)。但是不能保证他们会以任何固定的顺序到达那个点!

      所以总的来说:不要依赖它。

      【讨论】:

        【解决方案3】:

        不,互斥锁只防止两个线程同时访问变量。它不会影响线程调度顺序或执行时间,无论出于何种目的和目的,都可以假定它们是随机的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-09
          • 2012-07-09
          • 1970-01-01
          • 2011-08-05
          • 1970-01-01
          • 2022-01-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多