我有一个调用线程的 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_cancel,可以使用由主线程设置并由线程 1 读取的全局标志。此外,您可以使用任何 IPC 方法,例如建立 pipe在线程之间。
关于c - 在 C 中终止一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6836894/