我有许多线程函数foo
运行(std::thread t([&]() { foo(a); }
):的std ::原子能和std :: lock_guard或只的std :: lock_guard
void foo(int a)
{
if (x && y != a)
{
++x;
y = a;
vec.push_back(std::chrono::high_resolution_clock::now());
}
}
我需要保护int x
,int y
和std::vector<> vec
对竞争条件。 什么是最佳解决方案。
定义x
和y
为std::atomic
,推动以vec
之前使用std::lock_guard(mutex)
。
或std::lock_guard
为if
声明的全身?
或者也许有更好的解决方案?
就个人而言,我会锁定整个事情,因为整个操作看起来应该不是交错的。 – NathanOliver
在测试'y!= 5'之后,你是否介意另一个线程在你到达'y = 5'行之前是否改变'y'? – Galik