在循环中创建新线程是否安全? [英] Is it safe to create new thread in a loop?

查看:328
本文介绍了在循环中创建新线程是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在while循环内创建新线程是否安全?我已经尝试过这种方式:

Is it safe to create new thread inside while loop? I have tried this way:

std::thread thread(ClientLoop,clientSocket)

但是一旦函数返回,它就会引发错误.

But as soon as the function return it throws the error.

while (true){
    cout << "Waiting for new connections" << endl;
    clientSocket = accept(listenSocket, nullptr, nullptr);
    cout << "Client connected" << endl;
    new thread(ClientLoop,clientSocket);                
}   

以这种方式工作,但是我想知道是否没有内存泄漏.谢谢.

This way it works, but I wonder if there are no memory leaks. Thanks.

推荐答案

函数返回后立即引发错误

as soon as the function return it throws the error

实际上,您一定不能销毁可连接的线程对象.如果不需要稍后再等待线程完成,请分离它:

Indeed, you mustn't destroy a joinable thread object. If you have no need to wait for the thread's completion later, then detach it:

std::thread thread(ClientLoop,clientSocket);
thread.detach();
// OK to destroy now

例如,如果以后需要加入它,则必须将其存储在循环之外的某个地方,例如

If you will need to join it later, then you'll have to store it somewhere that persists beyond the loop, for example

std::vector<std::thread> threads;
while (whatever){
    clientSocket = accept(listenSocket, nullptr, nullptr);
    threads.emplace_back(ClientLoop,clientSocket);
}

// later
for (std::thread & t : threads) {
    t.join();
}

// OK to destroy now
threads.clear();

以这种方式工作,但是我想知道是否没有内存泄漏.

This way it works, but I wonder if there are no memory leaks.

是的,这很漏水.每个new都会创建一个线程对象,您无需删除指针或将其分配给要照顾的智能指针就丢弃该指针.如评论中所述,它不仅会泄漏内存,还会泄漏线程句柄,这在某些系统上是更为稀缺的资源.因此一段时间后,您可能会发现无法再启动任何线程.

Yes, that's leaky. Each new creates a thread object, and you discard the pointer without deleting it or assigning it to a smart pointer to take care of. As mentioned in the comments, it not only leaks memory, but also thread handles, which on some systems are a more scarce resource; so after a while you might find that you can't launch any more threads.

分离线程是使它在后台运行而不泄漏的一种方式.这将导致线程在完成时释放其资源.

Detaching a thread is the way to leave it running in the background without leaking. This causes the thread to release its resources when it finishes.

这篇关于在循环中创建新线程是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆