嗨我正在嘗試找出終止工作線程的最佳和平方式。我有以下代碼:終止工作線程的正確方法
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」是真實的,通知其他工人的線程更好的辦法?
感謝
「......最安靜的方式......」有沒有暴力的方式? –
請使用'unique_ptr'代替手動指針追蹤。 – GManNickG
非敵對殺是我認爲他/她的意思 – ApolloSoftware