gpt4 book ai didi

multithreading - c++ 11线程,为什么该程序在 Release模式下继续无限运行

转载 作者:行者123 更新时间:2023-12-03 13:15:34 24 4
gpt4 key购买 nike

#include <iostream>
#include <thread>


int x = 0;
int y = 0;

void f()
{
std::cout <<"f called\n";

static int c = 0;
while(y == 0)
{
++c;
}
std::cout << "c=" << c << std::endl;
std::cout << "x=" << x << std::endl;
}

void g()
{
std::cout <<"g called\n";
x = 42;
y = 1;
}

int main()
{
std::thread t1(f);
std::thread t2(g);

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

return 0;
}

当从另一个线程设置了标志y时,f应该打印'x = 42'(嗯,它也可以打印x = 0,但这不是问题)

在 Debug模式下运行时,它可以按预期工作:
f called
g called
c=80213
x=42

但是在 Release模式下,第二个线程似乎死机,程序永远不会结束:
f called
g called

有人可以解释为什么吗?

PS。
该程序使用mignw g++ 4.8.0编译

最佳答案

C++ 11线程内存模型不要求一个线程中的代码将看到由另一个线程中的代码引起的内存更改,除非:

  • 两个线程通过使用std::mutex同步对内存的访问。也就是说,接收线程必须等待写入线程持有的互斥量。并且在释放该互斥锁之前,写入线程必须已写入数据。
  • 有问题的内存由std::atomic控制,并且使用适当的原子内存访问对其进行写入和读取。

  • 如果这两种情况都不起作用,则一个线程尝试从内存中读取的任何尝试(可能被另一个线程修改)都被视为“数据竞争”。因此会导致未定义的行为。

    关于multithreading - c++ 11线程,为什么该程序在 Release模式下继续无限运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18375306/

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