线程退出未定义行为

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <pthread.h>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker_thread() {
    std::unique_lock<std::mutex> lock(mtx);
    
    // 如果在此处被pthread_cancel,会导致问题
    cv.wait(lock, []{ return ready; });
    
    std::cout << "Worker thread completed" << std::endl;
}

int main() {
    std::thread t(worker_thread);
    
    // 模拟一些工作
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    
    // 危险操作:在条件变量等待时取消线程
    pthread_cancel(t.native_handle());
    
    t.join();  // 这里可能会出现问题
    
    return 0;
}

在 C++11 中,当线程在条件变量上等待时被 pthread_cancel 取消,确实会导致未定义行为,通常会使程序调用 std::terminate;最终导致崩溃

posted on 2025-10-24 16:15  邗影  阅读(4)  评论(0)    收藏  举报

导航