2017-08-08 64 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'; 
} 

線程發出信號結束其功能和線程設置一個標誌,讓主函數知道它是安全的退出。

如果你有多個線程,你可以使用一個原子計數器當它達到零時退出。