MOH*_*MED 2 c multithreading pthreads
可能重复:
在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;
}
Run Code Online (Sandbox Code Playgroud)
iab*_*der 10
你可以使用pthread_cancel()来杀死一个线程:
int pthread_cancel(pthread_t thread);
Run Code Online (Sandbox Code Playgroud)
请注意,线程可能没有机会进行必要的清理,例如,释放锁,释放内存等等.因此,您应首先使用pthread_cleanup_push()添加清除函数,这些函数将在取消线程时调用.来自man pthread_cleanup_push(3):
这些函数操纵调用线程的线程消除清理处理程序堆栈. 清理处理程序是在取消线程时(或在下面描述的各种其他情况下)自动执行的函数 ; 例如,它可能会解锁一个互斥锁,以便它可以被进程中的其他线程使用.
关于是否阻止线程被取消的问题,不保证,请注意手册也提到:
由pthread_setcanceltype(3)确定的线程的取消类型可以是异步的或延迟的(新线程的默认值).异步可取消性意味着可以随时取消线程(通常是立即取消,但系统不保证这一点).延迟可取消性意味着取消将被延迟,直到线程下一次调用作为取消点的函数.
所以这意味着唯一保证的行为是线程将在调用后的某个点被取消pthread_cancel().
注意:如果你不能改变线程代码来添加清理处理程序,那么你唯一的另一个选择就是用pthread_kill()来杀死线程,但是由于上述原因,这是一个非常糟糕的方法.