我很有趣,互斥锁(不取决于特定语言)是否必须保持锁定/解锁的顺序?
这是示例C ++代码:
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
}
}
在VS2013服务器时间在Debug和Release(有一些更改,未优化代码)下运行此代码后,我总是只在第一个断点处命中。
不,没有关于订单的保证。它恰好以这种方式在您的计算机上工作(例如,在我的计算机ok
上并非总是如此)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句