更新时间:2021-12-31 00:43:28
UB 这与finished
有关.您可以使finished
类型为std::atomic<bool>
来解决此问题.
Two threads, accessing a non-atomic, non-guarded variable are U.B. This concerns finished
. You could make finished
of type std::atomic<bool>
to fix this.
我的解决方法:
#include <iostream>
#include <future>
#include <atomic>
static std::atomic<bool> finished = false;
int func()
{
size_t i = 0;
while (!finished)
++i;
return i;
}
int main()
{
auto result=std::async(std::launch::async, func);
std::this_thread::sleep_for(std::chrono::seconds(1));
finished=true;
std::cout<<"result ="<<result.get();
std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}
输出:
result =1023045342
main thread id=140147660588864
有人可能会认为'这是bool
–大概一点.这怎么可能是非原子的? (我是从多线程开始的.)
Somebody may think 'It's a bool
– probably one bit. How can this be non-atomic?' (I did when I started with multi-threading myself.)
但是请注意,缺乏训练不是std::atomic
给您的唯一东西.它还使来自多个线程的并发读写访问权限得到了明确定义,从而阻止了编译器假设重新读取该变量将始终看到相同的值.
But note that lack-of-tearing is not the only thing that std::atomic
gives you. It also makes concurrent read+write access from multiple threads well-defined, stopping the compiler from assuming that re-reading the variable will always see the same value.
使bool
不受保护,没有原子性会导致其他问题:
Making a bool
unguarded, non-atomic can cause additional issues:
atomic<bool>
和memory_order_relaxed
可以存储/加载,而volatile
则不能.即使实际上它可以在实际的C ++实现中使用,它也将是UB.)atomic<bool>
with memory_order_relaxed
store/load would work, but where volatile
wouldn't. Using volatile for this would be UB, even though it works in practice on real C++ implementations.)为防止这种情况发生,必须明确告知编译器不要这样做.
To prevent this to happen, the compiler must be told explicitly not to do.
对于关于volatile
与该问题的潜在关系的不断发展的讨论,我感到有些惊讶.因此,我想花掉我的两分钱:
I'm a little bit surprised about the evolving discussion concerning the potential relation of volatile
to this issue. Thus, I'd like to spent my two cents: