Mutex lock/unlock order

2019-01-28 09:48发布

问题:

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.

回答1:

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).



回答2:

No, there are no guarantees about the order.

You can try with condition variables:

#include <thread>
#include <vector>
#include <array>
#include <list>
#include <mutex>
#include <condition_variable>

const int MAX = 100; //***
std::mutex testVecMtx;
std::vector<int> testVec;
std::array<std::condition_variable,MAX+1> Notifications; //***
int Current = 0; //***

void testPush(int v){
  std::unique_lock<std::mutex> lk(testVecMtx);
  while (v != Current){
    Notifications[v].wait(lk);
  }

  testVec.push_back(v);
  Current++;

  if (v != MAX)
    Notifications[v+1].notify_all();
}

int main(){
  std::list<std::thread> thList;

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

  for (auto &i : thList){
        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...
//    std::cout<<"Ok"<<std::endl;
  }
  else{
    int stop = 432; // ...and 2nd here
  }
}


标签: c++ order mutex