可能重复:
如何在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_join
和pthread_attr_setdetachstate
... 创建一些机制来告诉线程现在需要退出,并调用pthread_join
来清理使用的资源。 - user1551592pthread_cancel(pthread_t thread);
是否可能会导致阻塞,如果线程函数正在执行系统调用? - MOHAMED