【发布时间】:2012-02-14 17:23:01
【问题描述】:
我试图了解如何在 c++ 中将互斥锁与对象一起使用。我有以下(琐碎的)多线程代码用作速度测试:
struct Rope{
int n, steps, offset;
//std::mutex mut;
Rope() {}
Rope(int n, int steps, int offset) : n(n), steps(steps), offset(offset) {}
void compute(){
double a[n];
for (int i=0; i<n; i++)
a[i] = i + offset;
for (int step=0; step<steps; step++)
for (int i=0; i<n; i++)
a[i] = sin(a[i]);
}
};
void runTest(){
int numRuns = 30;
int n = 10000;
int steps = 10000;
std::vector<Rope> ropes;
std::vector<std::thread> threads;
for (int i=0; i<numRuns; i++)
ropes.push_back(Rope(n, steps, i));
for (auto& r : ropes)
threads.push_back(std::thread(&Rope::compute, r));
for (std::thread& t : threads)
t.join();
}
代码按原样运行良好,并且在我的 4 核机器上实现了约 4 倍的加速。当然,我没有在绳索中存储任何东西,所以不需要互斥锁。如果我现在假设我确实有一些需要保护的数据,我想将一个互斥锁附加到 Rope 并(例如)在 compute() 循环中调用 std::lock_guard 。但是,如果我取消注释互斥锁,我会收到一堆关于赋值和复制运算符“使用已删除函数”的编译器错误。我在安全锁定对象的目标中缺少什么?
【问题讨论】: