我正在编写一个简单的例子来测试C ++ Threads和Mutexes:
#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 ++ Mutexs真的能保证相互排斥,还是我错过了什么?