2017-08-16 6 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

関連する問題