gpt4 book ai didi

c++ - 终止由 header 创建的线程

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:52 26 4
gpt4 key购买 nike

我正在制作一个小程序来理解线程的流动。我陷入了运行时错误。我花了 2 天时间才弄清楚给出运行时错误的函数有一个线程在其他地方运行。现在,我需要正确关闭该线程,以便我的主函数能够正确终止。

这是我做的一个例子;

void main()
{
int n = fun2();
cout << n;
}

int fun2()
{
thread parallel(fun3);
return 2;
}

void fun3()
{
while (smth)
{
...
}
}

fun3() 顺便做了文件读取部分。我阅读了与此问题相关的多个问题,但实际上没有一个有帮助,其中大多数都在使用我不理解的 HANDLE 东西。如果有其他方法可以同时执行2个函数,我想知道。

如有任何帮助,我们将不胜感激。

最佳答案

您收到运行时错误,因为 std::thread 将在未连接或分离时执行 std::terminate()。您的 main 函数在没有加入 fun2() 生成的线程的情况下完成。一个简单的修复方法就是像这样在第二个函数中加入线程:

void main()
{
int n = fun2();
cout << n;
}

int fun2()
{
thread parallel(fun3);
parallel.join() // wait for the thread to finish
return 2;
}

void fun3()
{
while (smth)
{
...
}
}

关于c++ - 终止由 <thread> header 创建的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820779/

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