Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การ Terminate Thread ใน C++11

C++11 ไม่มีฟังก์ชัน terminate thread โดยตรง (unsafe) ใช้ pattern ร่วมกับ std::promise/std::future เพื่อส่งสัญญาณให้ thread หยุดเอง

กลไก

  1. สร้าง std::promise<void> ใน main thread
  2. ดึง std::future<void> ให้ worker thread
  3. Worker thread ตรวจ future.wait_for() เป็นระยะ
  4. Main thread เรียก promise.set_value() เพื่อส่งสัญญาณหยุด

โค้ดตัวอย่าง

void threadFunc(future<void> fut) {
    cout << "Thread started\n";
    while (fut.wait_for(chrono::milliseconds(1)) == future_status::timeout) {
        cout << "Working...\n";
        this_thread::sleep_for(chrono::milliseconds(500));
    }
    cout << "Thread terminated\n";
}

int main() {
    promise<void> exitSignal;
    future<void> fut = exitSignal.get_future();
    thread th(threadFunc, std::move(fut));

    this_thread::sleep_for(chrono::seconds(7));
    cout << "Stopping thread...\n";
    exitSignal.set_value(); // ส่งสัญญาณ
    th.join(); // รอจบ
    cout << "Main continues\n";
}

ผลลัพธ์

Thread started
Working... (ซ้ำหลายครั้ง)
Stopping thread...
Thread terminated
Main continues

วิธีนี้ปลอดภัย ให้ thread ทำ cleanup ก่อนจบ