gpt4 book ai didi

c++ - C++ 11 中的锁是否保证访问数据的新鲜度?

转载 作者:太空狗 更新时间:2023-10-29 21:33:04 26 4
gpt4 key购买 nike

通常,当使用由多个线程并发访问的 std::atomic 类型时,不能保证线程在访问它们时会读取“最新”值,并且线程可能会从缓存中获取陈旧值或任何旧值.获取最新值的唯一方法是 compare_exchange_XXX 等函数。 (参见问题 herehere)

#include <atomic>

std::atomic<int> cancel_work = 0;
std::mutex mutex;

//Thread 1 executes this function
void thread1_func()
{
cancel_work.store(1, <some memory order>);
}


// Thread 2 executes this function
void thread2_func()
{
//No guarantee tmp will be 1, even when thread1_func is executed first
int tmp = cancel_work.load(<some memory order>);
}

但是我的问题是,当使用互斥量和锁时会发生什么?我们对访问的共享数据的新鲜度有任何保证吗?

例如假设线程1和线程2同时运行,线程1先获得锁(先执行)。它是否保证线程 2 将看到修改后的值而不是旧值?在这种情况下共享数据“cancel_work”是否是原子的重要吗?

#include <atomic>

int cancel_work = 0; //any difference if replaced with std::atomic<int> in this case?
std::mutex mutex;

// Thread 1 executes this function
void thread1_func()
{
//Assuming Thread 1 enters lock FIRST
std::lock_guard<std::mutex> lock(mutex);

cancel_work = 1;
}


// Thread 2 executes this function
void thread2_func()
{
std::lock_guard<std::mutex> lock(mutex);

int tmp = cancel_work; //Will tmp be 1 or 0?
}

int main()
{
std::thread t1(thread1_func);
std::thread t2(thread2_func);

t1.join(); t2.join();

return 0;
}

最佳答案

是的,使用互斥/锁保证 thread2_func() 将获得修改后的值。

但是,根据 std::atomic 规范:

The synchronization is established only between the threads releasing and acquiring the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.

因此您的代码也可以使用获取/发布逻辑正常工作。

#include <atomic>

std::atomic<int> cancel_work = 0;

void thread1_func()
{
cancel_work.store(1, std::memory_order_release);
}

void thread2_func()
{
// tmp will be 1, when thread1_func is executed first
int tmp = cancel_work.load(std::memory_order_acquire);
}

关于c++ - C++ 11 中的锁是否保证访问数据的新鲜度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52762327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com