c++ - Boolean stop signal between threads
问题描述
What is the simplest way to signal a background thread to stop executing?
I have used something like:
volatile bool Global_Stop = false;
void do_stuff() {
while (!Global_Stop) {
//...
}
}
Is there anything wrong with this? I know for complex cases you might need "atomic" or mutexes, but for just boolean signaling this should work, right?
解决方案
std::atomic
is not for "complex cases". It is for when you need to access something from multiple threads. There are some myths about volatile
, I cannot recall them, because all I remember is that volatile
does not help when you need to access something from different threads. You need a std::atomic<bool>
. Whether on your actual hardware accessing a bool
is atomic does not really matter, because as far as C++ is concerned it is not.
推荐阅读
- javascript - Webpack 4 - 多个条目 - 每个条目多个实例
- css - Wordpress 自定义 Html - 跳转到锚点然后滚动
- angular - 如何将两个值放在 html 列表中,然后只读取一个以显示在
{{ }}
- android - 签名的 .apk 在调试 .apk 工作正常的地方不起作用
- powershell - VSCode 中的 Powershell 终端编码
- r - 为什么过滤器功能需要这么多时间来提供输出[下面的示例],有没有更好的过滤器方法?
- php - 在 Woocommerce 结帐中从未登录用户中删除 Aelia EU 增值税号字段
- javascript - Javascript 更改标题然后 f12 看到变化,但是 ctrl + u 没有看到任何变化
- html - 如何使用 href 目标显示 div 和嵌套 div?
- docker - 将容器图像标签与摘要一起使用