我正在编写一个简单的示例来测试 C++ 线程和互斥量:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
const int num_th = 50;
const int num_vals = 20;
const int num_it = 1000;
class MyVector {
public:
MyVector(int size): vals_(size, 0), idx_(0), mtx_() {}
void inc()
{
mtx_.lock();
for(int i=0; i<num_it; i++)
{
vals_[idx_]++;
idx_= (idx_+1) % num_vals;
}
mtx_.unlock();
}
int getVal(int idx) {return vals_[idx];}
private:
std::mutex mtx_;
int idx_;
std::vector<int> vals_;
};
int main(int argc, char *argv[])
{
MyVector m(num_vals);
std::thread t1[num_th];
for(int i=0; i<num_th; i++)
t1[i] = std::thread(&MyVector::inc, &m);
for(int i=0; i<num_th;i++)
t1[i].join();
for(int i=0; i<num_vals; i++)
std::cout<<" "<<m.getVal(i);
return 0;
}
执行后,所有值应该相同,但这是输出:
2053 2063 2054 2038 2029 2038 2036 2043 2048 2049 2048 2055 2055 2050 2050 2051 2051 2055 2042 2066
C++ 互斥锁真的保证互斥,还是我漏掉了什么?
最佳答案
5gon12eder 是对的。使用 -pthread 问题得到解决并且输出正确:
2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500
我很惊讶您在使用线程时需要为编译器使用“-pthread”选项,并且没有编译或链接错误。
PS:编译器为gcc,操作系统为Linux(g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4)
关于c++ - C++ Mutex 是否保证避免竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32552990/