C++11 không có thread.terminate(). Dùng std::promise<void> + std::future<void> để gửi tín hiệu dừng.
Cơ chế
- Main tạo
promise, lấyfuture = promise.get_future(). - Thread nhận
future, lặp kiểm trafuture.wait_for(timeout) == timeout. - Main gọi
promise.set_value()để báo dừng. - Thread thoát vòng lặp, kết thúc.
Ví dụ
#include <thread>, <future>, <chrono>, <iostream>
using namespace std;
void worker(future<void> fut) {
cout << "Thread start\n";
while (fut.wait_for(1ms) == future_status::timeout) {
cout << "Working...\n";
this_thread::sleep_for(500ms);
}
cout << "Thread stopped\n";
}
int main() {
promise<void> exitSignal;
auto fut = exitSignal.get_future();
thread t(worker, move(fut));
this_thread::sleep_for(7s);
cout << "Stopping thread...\n";
exitSignal.set_value();
t.join();
cout << "Main done\n";
}