如何关闭线程分离C ++? [英] How to close thread detach C++?
本文介绍了如何关闭线程分离C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以分离状态启动了线程. 如何从主函数关闭线程?
I launched thread as detach. How to close thread from main function?
void My()
{
// actions
}
void main()
{
std::thread thr7(receive);
thr7.detach();
// close ?
}
推荐答案
简短答案:
使用共享变量来通知线程何时停止.
Short Answer:
Use a shared variable to signal threads when to stop.
除非调用其他方法,否则一旦调用detach
,就不能直接从其父级调用join
或terminate
线程.
You cannot call join
or terminate
a thread directly from its parent once detach
is called unless you use some other methods.
看看下面的代码(简单而又不太有意义),它应该显示出一种简单的方式来完成您要问的事情:
Take a look at the following code (over simple and not very meaninful) which should show a simple way of doing what you are asking:
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
std::mutex mu;
std::condition_variable cv;
bool finished = false;
void threadFunc()
{
while(!finished)
{
std:: cout << "Thread doing work \n";
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
std::cout << "End of Thread \n";
}
int main()
{
{
std::thread t1(threadFunc);
t1.detach(); // Call `detach` to prevent blocking this thread
} // Need to call `join` or `detach` before `thread` goes out of scope
for (int i = 0; i < 5; ++i){
std::this_thread::sleep_for(std::chrono::milliseconds(20));
std::cout << "Main doing stuff: \n";
}
std::cout << "Terminating the thread\n";
std::unique_lock<std::mutex> lock(mu);
finished = true;
cv.notify_all();
std::cout << "End of Main\n";
return 0;
}
您使用共享变量来告诉线程何时终止其执行.
You use a shared variable to tell the threads when to terminate its execution.
这篇关于如何关闭线程分离C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文