2017-08-08 90 views
0

我启动线程作为detach。 如何从主函数关闭线程?如何关闭线程分离C++?

void My() 
{ 
    // actions 
} 


void main() 
{ 

std::thread thr7(receive); 
thr7.detach(); 

// close ? 

} 
+5

反问题:你为什么分开它?一旦分离,它是......好..分离 – user463035818

+1

你能否详细说明你的意思是“接近”?你想给线程一个信号,它应该退出吗? –

+1

您无法关闭它。你必须以编程方式结束其角色(即功能必须达到其结束)。也许用一个'停止的'布尔(信号量)或类似的东西。 –

回答

3

如果我理解正确的话,你要告诉线程退出的无限循环和退出?

然后一个简单的布尔值std::atomic对象就是所有需要的。

您将其初始化为某个值(例如true),并在线程循环中将其设为该值。一旦你想让线程退出,你改变它的值(到false),然后当线程循环迭代时它会注意到它并打破循环并继续清理并退出。

+0

螺纹: 无效我(){ 而 (end_thr){// 一些代码 } 其他{ 的std ::原子; } } 对不对? –

+0

...并在'main()'join()'线程中(设置原子之后)以确保它在离开main()之前结束。 – Persixty

+1

@Persixty不可能或不需要分离线程。 –

2

除非使用其他一些方法,否则一旦调用detach,就不能调用jointerminate直接从其父项的线程。

看看下面的代码(在简单,不是非常meaninful),它应该表现出做一个简单的方法你问:

#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

您可以控制线是这样的:

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'; 
} 

线程发出信号结束其功能和线程设置一个标志,让主函数知道它是安全的退出。

如果你有多个线程,你可以使用一个原子计数器当它达到零时退出。