在C++中终止线程 [英] terminating a thread in C
本文介绍了在C++中终止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个调用线程的C程序。
iret1 = pthread_create( &thread1, NULL, readdata, NULL);
iret2 = pthread_create( &thread2, NULL, timer_func, NULL);
pthread_join(thread2, NULL);
线程%2在执行某个函数后返回,之后我想停止线程%1的执行。我应该怎么做?
推荐答案
您可以使用pthread_cancel
:
pthread_cancel(thread1);
和readdata
中:
/* call this when you are not ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
/* call this when you are ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
有关详细信息,请参阅pthread_cancel man page-其中包含一个示例。
如果您不想使用pthread_ancel,您可以使用由主线程设置并由线程1读取的全局标志。此外,您可以使用任何IPC方法,如在线程之间建立pipe。
这篇关于在C++中终止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文