C++11线程强制退出线程的接口(也不赞成这样退出),只能自己实现退出逻辑,以下示例是开发中个人觉得比较简单好用的一种方式:
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <functional>
#include <atomic>
class Test {
public:
Test() {
cnt_.store(0);
exit_.store(false);
for (int i = 0; i < 5; ++i)
std::thread(std::bind(&Test::Fn1, this)).detach();
};
void Fn1() {
cnt_++;
while (1)
{
if (exit_)
break;
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
std::cout << "thread:" << std::this_thread::get_id << ",exit!" << std::endl;
cnt_--;
}
~Test() {
std::this_thread::sleep_for(std::chrono::seconds(4));
exit_.store(true);
while (cnt_);
};
private:
std::condition_variable cv_;
std::mutex mtx_;
std::atomic<int> cnt_;
std::atomic<bool> exit_;
};
int main() {
Test* t = new Test();
delete t;
getchar();
return 0;
}