甚至在使用std::原子类型后也遇到了种族歧视
Encountered race even after using std::atomic types
你能告诉我以下代码是否是线程安全的吗?
我想我遇到了一个竞争条件,因为即使我已经从GUI中将params.b的值设置为true,Task2也不会被执行。
struct params {
params() {}
~params() {}
atomic_bool a;
atomic_bool b;
};
struct driver {
driver() {}
~driver() {}
params myParams;
void tFun() {
while (1) {
if (myParams.a) { /* DoTask1 */ }
if (myParams.b) { /* DoTask2 */ }
}
}
void DoSome() {
std::thread t(&driver::tFun, this);
t.detach();
while (1) {
myParams.a = fromGui.val;
myParams.b = fromGui.val;
}
}
};
int main() {
driver myDriver;
myDriver.DoSome();
return 0;
}
请执行我的"fromGui.val"用法,它应该指示该值将从GUI加载。
我看到的情况是fTun()
函数和DoSome()
:之间存在竞争
例如:
1. DoSome() sets a,b true
2. tFun() executes in while loop, as a is true, it starts DoTask1
2. DoSome() sets a,b to false
3. tFun() finishes DoTask1 and come to check myParams.b which is false;
DoTask2 is ignored!!
4. loop continues to step 1
如果您总是将a,b设置为true,那么就没有可比较的竞争,任务DoTask1 & DoTask2
都应该执行
我在这里找不到任何真正的竞争条件,但我认为这段代码可能无法在所有操作系统上正常运行。
让我们看看提高收益率可以解决问题。
void tFun() {
while (1) {
bool nop = false;
if (myParams.a) { /* DoTask1 */ }
else { nop = true; }
if (myParams.b) { /* DoTask2 */ }
else { nop = true; }
if (nop) { std::this_thread::yield(); }
}
}
void DoSome() {
std::thread t(&driver::tFun, this);
t.detach();
while (1) {
myParams.a = fromGui.val;
myParams.b = fromGui.val;
std::this_thread::yield();
}
}
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何从文本文件中读取数值,直到遇到字符类型?
- 我在 C++ 代码中遇到错误警告:控制到达非空函数 [-Wreturn 类型] 的末尾
- 我在 c++ 中声明字符串类型时遇到问题
- 在没有宏的情况下在 C++98 中创建类型列表时遇到问题
- 我的程序C++找到三角形的类型,我的if-else语句遇到问题
- 我在一个简单的参数依赖查找/模板类型推断问题方面遇到问题
- 甚至在使用std::原子类型后也遇到了种族歧视
- 如何正确使用模板?我在使用模板时遇到数据类型问题<>
- 读取int*类型的结构属性值时遇到问题
- 在声明包含类型的对象时遇到问题
- 从文本文件中读取已创建的结构类型时遇到问题