可能的重复:
杀死 pthread 中的线程 https://stackoverflow.com/questions/2084830/kill-thread-in-pthread
在包含线程启动的源代码之后,过了一会儿我想杀死它。怎么做 ?无需对线程函数进行任何更改
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_t test_thread;
void *thread_test_run (void *v) // I must not modify this function
{
int i=1;
while(1)
{
printf("into thread %d\r\n",i);
i++;
sleep(1);
}
return NULL
}
int main()
{
pthread_create(&test_thread, NULL, &thread_test_run, NULL);
sleep (20);
// Kill the thread here. How to do it?
// other function are called here...
return 0;
}
您可以使用pthread_cancel() http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html杀死一个线程:
int pthread_cancel(pthread_t thread);
请注意,线程可能没有机会进行必要的清理,例如释放锁、释放内存等。所以您应该首先使用pthread_cleanup_push()
添加线程取消时将调用的清理函数。来自男人pthread_cleanup_push(3) http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cleanup_push.3.html:
这些函数操纵调用线程的堆栈
线程取消清理处理程序。清理处理程序是
当线程被取消时自动执行的函数(或者
在下述各种其他情况下);可能,对于
例如,解锁互斥体,以便其他线程可以使用它
正在进行中。
关于线程是否阻塞是否会被取消的问题,不能保证,注意手册中也提到了这一点:
线程的取消类型,由 pthread_setcanceltype(3) 确定,
可能是异步或延迟(默认为 new
线程)。异步可取消性意味着线程
可以随时取消(通常会立即执行,但系统会
不保证这一点)。延迟取消意味着取消
将被延迟,直到线程下一次调用一个函数
取消点。
所以这意味着唯一保证行为是线程将在调用后的某个时刻被取消pthread_cancel()
.
Note:
如果您无法更改线程代码以添加清理处理程序,那么您唯一的其他选择就是使用以下命令终止线程pthread_kill() http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_kill.html,然而,由于上述原因,这是一种非常糟糕的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)