Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kết thúc thread an toàn trong C++11 (promise/future)


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ế

  1. Main tạo promise, lấy future = promise.get_future().
  2. Thread nhận future, lặp kiểm tra future.wait_for(timeout) == timeout.
  3. Main gọi promise.set_value() để báo dừng.
  4. 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";
}