我启动了线程作为分离。 如何从主函数关闭线程?
error_reporting(1);
答案 0 :(得分:3)
如果我理解正确,你想告诉线程退出无限循环并退出吗?
然后只需要一个简单的布尔std::atomic
对象。
您将其初始化为某个值(比如true
),并在线程循环中将其初始化为该值。一旦你想让线程退出,你就改变了值(到false
)然后在线程循环迭代时接下来它将注意到并打破循环并继续清理并退出。
答案 1 :(得分:3)
使用共享变量向线程发出停止信号。
除非您使用其他方法,否则在调用join
后,您无法直接从其父级调用terminate
或detach
个线程。
看看下面的代码(过于简单而不是非常有意义),它应该显示一个简单的方法来做你想要的:
#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;
}
使用共享变量告诉线程何时终止执行。
答案 2 :(得分:2)
你可以像这样控制线程:
std::atomic_bool running = false; // set to stop thread
std::atomic_bool closed = false; // set by thread to indicate it ended
void detached_thread_function()
{
running = true;
// acquire resources
while(running)
{
std::cout << "running" << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// release resources
// set after all resources released
closed = true;
}
int main()
{
std::thread(detached_thread_function).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "stopping detached thread" << '\n';
running = false; // stop thread
while(!closed) // you could code a timeout here
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// or use a condition variable?
std::cout << "end program" << '\n';
}
线程被发信号以结束其功能,线程设置一个标志,让main函数知道退出是安全的。
如果您有多个线程,则可以使用原子计数器在达到零时退出。