我要杀死某个线程,知道这个线程的ID,请问应该如何做。

ypzhong 2014-05-07 11:22:43
测过在线程的信号处理函数里调用pthread_exit()是行不通的。
...全文
378 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ypzhong 2014-05-07
  • 打赏
  • 举报
回复
事实上我那个线程是堵塞读取网络套接字数据,循环遍历某个变量也是行不通的,我希望用linux的系统函数功能。在我某个时刻无论如何让这个线程挂掉。若能给出正确方案,分全给。
ypzhong 2014-05-07
  • 打赏
  • 举报
回复
确实对我有用,怕网站以后没用了,把关键地方复制过来,用来以后忘了备用。
#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <unistd.h> 
void* func(void *) 
{ 
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //允许退出线程 
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); //设置立即取消 
  while (1) 
  { 
    //操作 ; 
  } 
  return NULL; 
} 
int main(int argc, char *argv[]) 
{ 
  pthread_t thrd; 
  pthread_attr_t attr; 
  pthread_attr_init(&attr); 
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
  if( pthread_create(&thrd, &attr, func, NULL) ) 
  { 
    perror( "pthread_create error "); 
    exit(EXIT_FAILURE); 
   } 
   if( !pthread_cancel(thrd) )  
   { 
     printf( "pthread_cancel OK\n " ); 
   } 
   sleep( 10 ); 
   return 0; 
}
上面程序并不会将子线程取消 why? ------- 因为没有遇见或是设置引起Cancelation动作的取消点, 可以在调用了pthread_cancel函数后,调用pthread_join函数以获得取消点,使线程退出。 *************************************************************************** 再看下面一段程序: pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_testcancel();/*the thread can be killed only here*/ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); 这个是代码里面摘录下来的代码,什么情况下 线程能被杀掉呢? 因为 这段代码 在 线程的循环里面,那每次执行到这段的时候,为什么都没有被杀掉呢? ------- 简单理解就是,两个线程T1和T2,如果T1发送cancel信号给T2,则T2默认会在取消点退出。取消点是固定的地方,只要thread_join()、pthread_testcancel()、pthread_cond_wait()、 pthread_cond_timedwait()、sem_wait()、sigwait()等函数以及read()、write()等会引起阻塞的系统调用都是Cancelation-point。 假设T2在一个循环中,这个循环中没有取消点,那么怎么办?收到cancel信号也没办法退出。这时就用pthread_testcancel()来创造一个取消点,如果有cancel信号就退出,没有就继续运行。

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧