Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c++ - Mutex lock/unlock order

I am interesting whether mutexes(not depending on particular language) must keep the order of lock/unlock?
Here is example C++ code:

std::mutex testVecMtx;
std::vector<int> testVec;

void testPush(int v){
  std::lock_guard<std::mutex> lk(testVecMtx);

  if (testVec.empty()){
    // wait some time to get more threads waiting on testVecMtx
    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
  }

  testVec.push_back(v);
}

void Main_TEST(){
  std::list<std::thread> thList;

  for (int i = 0; i < 1000; i++){
    thList.push_front(std::thread(testPush, i));
  }

  for (auto &i : thList){
    if (i.joinable()){
        i.join();
    }
  }

  bool ok = true;

  for (int i = 0; i < (testVec.size() - 1) && ok; i++){
    ok = testVec[i + 1] - testVec[i] == 1;
  }

  if (ok){
    int stop = 243; // 1st breaking point here...
  }
  else{
    int stop = 432; // ...and 2nd here
  }
}

After running this code in VS2013 serveral times in Debug and Release(with some changes to get code not optimized out) mode I always get hit only on 1st breakpoint.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, there are no guarantees about the order. It just happens to work this way on your machine(for instance, on my computer ok is not always true).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...