简体   繁体   English

为什么我不能在while循环中创建线程?

[英]Why can't i create a thread in while loop?

I want to create a new thread inside a while loop but it makes the program instantly crash on start.我想在 while 循环中创建一个新线程,但它会使程序在启动时立即崩溃。 Any ideas on how to fix this?有想法该怎么解决这个吗?

#include <thread>
using namespace std;

void function1()
{

}

int main()
{
    while(true)
    {
        thread thread(function1);
    }
    return 0;
}

When your std::thread goes out of scope, its destructor is called.当您的std::thread超出范围时,将调用其析构函数。 The std::thread destructor calls std::terminate() if the thread is still active.如果线程仍处于活动状态,则std::thread析构函数调用std::terminate() You MUST join() or detach() the std::thread object before it is destroyed.您必须在std::thread对象被销毁之前join()detach()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM