2017-08-16 51 views
4

嗨我正在嘗試找出終止工作線程的最佳和平方式。我有以下代碼:終止工作線程的正確方法

class test{ 
    public: 
test() {} 
~test() {} 

std::atomic<bool> worker_done; 


int a; 
void pr() { 
    while (true) { 
     if (worker_done) { 
      break; 
     } 
     std::this_thread::sleep_for(std::chrono::milliseconds(500)); 
     printf("%d \n", a++); 
    } 
} 

std::thread* m_acqThread; 
void continuous() { 
    m_acqThread = new std::thread(&test::pr, this); 
} 

void stopThread(){ 
    if (m_acqThread) { 
     if (m_acqThread->joinable()) 
      m_acqThread->join(); 
     delete m_acqThread; 
     m_acqThread = nullptr; 
    } 
} 


}; 


int main(){ 

test t; 
t.continuous(); 

std::this_thread::sleep_for(std::chrono::milliseconds(2000)); 
t.worker_done = true; 

t.stopThread(); 


std::string str; 
std::cin.clear(); 
getline(std::cin, str); 
return 0; 

是否有被終止不是設置「worker_done」是真實的,通知其他工人的線程更好的辦法?

感謝

+0

「......最安靜的方式......」有沒有暴力的方式? –

+0

請使用'unique_ptr'代替手動指針追蹤。 – GManNickG

+1

非敵對殺是我認爲他/她的意思 – ApolloSoftware

回答

2

你有什麼是好的:如果你有一個thread程序打開時說開始,併爲你的程序關閉您需要停止它,使用atomic<bool>是這樣做的正確方法。

有可能也使用std::atomic_flag像這樣:

#include <thread> 
#include <atomic> 
#include <iostream> 

std::atomic_flag lock; 
int n = 0; 

void t() 
{ 
    while (lock.test_and_set()) 
    { 
     ++n; 
     std::this_thread::sleep_for(std::chrono::milliseconds(250)); 
    } 
} 

int main() 
{ 
    lock.test_and_set(); 
    std::thread t(&t); 
    std::this_thread::sleep_for(std::chrono::seconds(2)); 
    lock.clear(); 
    t.join(); 
    std::cout << n << std::endl; 
    std::cin.get(); 
} 

你可以閱讀有關why you might wish to choose atomic_flag over atomic<bool>,但我個人更喜歡使用atomic<bool>這樣的事情,因爲它只是更容易閱讀:

std::atomic<bool> runThread; 
int n = 0; 

void t() 
{ 
    while (runThread) 
    { 
     ++n; 
     std::this_thread::sleep_for(std::chrono::milliseconds(250)); 
    } 
} 

int main() 
{ 
    runThread = true; 
    std::thread t(&t); 
    std::this_thread::sleep_for(std::chrono::seconds(2)); 
    runThread = false; 
    t.join(); 
    std::cout << n << std::endl; 
    std::cin.get(); 
} 
+0

atomic_flag會更好嗎? – zzxyz

+0

至少'原子'便宜 – LWimsey

+1

原子標誌聽起來像是一個被遺忘的50歲的超級英雄。 – user4581301