c - 在 C 中终止一个线程

标签 c multithreading pthreads

我有一个调用线程的 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/

相关文章:

c - 理解scanf

c++ - 在 main 中使用指向变量的指针的 Pthread 段错误

python - 共享内存复杂的可写数据结构

python - 从Python并行批量读取文件

php - 我在处理数据时是否需要锁定我的记录以避免不一致?

c - 这个声明有什么问题?

c - 如何在c中使用pthread调用函数?

c - 为什么数组不从最后一个数字插入的地方继续?

c - OpenMP 优化?

c - 如何在头文件中引用 typedef?