Boost mutex order

2019-08-10 04:23发布

问题:

So having simple class

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;
};

and array of threads in infinite loops calling each one function

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

will they always call functions in the same order and only once per circle (by circle I mean will all boost threads run in same order each time so that each thread would Get() only once after one Set())?

回答1:

The threads should acquire the lock in the same order that they reach the scoped_lock constructor (I think). But there's no guarantee that they will reach that point in any fixed order!

So in general: don't rely on it.



回答2:

No. You can never make any assumptions of which order the threads will be served. This is nothing related to boost, it is the basics of multiprogramming.



回答3:

No, the mutex only prevents two threads from accessing the variable at the same time. It does not affect the thread scheduling order or execution time, which can for all intents and purposes be assumed to be random.