首页 > 解决方案 > 如何终止处于阻塞调用中间的 pthread?

问题描述

我有一些线程thr的任务是将数据从设备移动到文件。由于数据的大小,fwrite 需要几分钟才能完成。在此期间,用户可能不喜欢数据并选择清除它。在那种情况下,我的程序会收到通知,我想杀死这个 fwrite 中间的线程。我不担心数据的损坏,因为这一切都被认为是无关紧要的,但我确实需要文件描述符之类的东西才能对系统免费。我不能使用互斥体或在线程中有检查点来检查它是否应该结束,因为它都被这个单一的 fwrite 调用阻塞了。过早终止该线程的最合适方法是什么?

一些伪代码来说明场景:

void * thr() {
    //open a device for reading
    //and a file for writing

    fwrite(...); //this operation takes several minutes

    //close the device
    //and file

    pthread_exit(NULL);
}

main(){
    pthread_t thid;
    pthread_create(&thid, NULL, thr);

    //event that may need to terminate the thread early
}

标签: cmultithreadingpthreads

解决方案


推荐阅读