如何正确的终止正在运行的子线程

  最近开发一些东西,线程数非常之多,当用户输入Ctrl+C的情形下,默认的信号处理会把程序退出,这时有可能会有很多线程的资源没有得到很好的释放,造成了内存泄露等等诸如此类的问题,本文就是围绕着这么一个使用场景讨论如何正确的终止正在运行的子线程。其实本文更确切的说是解决如何从待终止线程外部安全的终止正在运行的线程

首先我们来看一下,让当前正在运行的子线程停止的所有方法

1.任何一个线程调用exit

2.pthread_exit

3.pthread_kill

4.pthread_cancel 

 

下面我们一一分析各种终止正在运行的程序的方法

 

任何一个线程调用exit

任何一个线程只要调用了exit都会导致进程结束,各种子线程当然也能很好的结束了,可是这种退出会有一个资源释放的问题.我们知道当一个进程终止时,内核对该进程所有尚未关闭的文件描述符调用close关闭,所以即使用户程序不调用close,在终止时内核也会自动关闭它打开的所有文件。没错,标准C++ IO流也会很好的在exit退出时得到flush并且释放资源,这些东西并不会造成资源的浪费(系统调用main函数入口类似于exit(main(argc,argv))).表面上似乎所有的问题都能随着进程的结束来得到很好的处理,其实并不然,我们程序从堆上分配的内存就不能得到很好的释放,如new ,delete后的存储空间,这些空间进程结束并不会帮你把这部分内存归还给内存.(本文初稿时,因基础不牢固,此处写错,事实上无论进程这样结束,系统都将会释放掉所有代码所申请的资源,无论是堆上的还是栈上的。(感谢ZKey的指导)。这种结束所有线程(包括主线程)的方式实际上在很多时候是非常可取的,但是对于针对关闭时进行一些别的逻辑的处理(指非资源释放逻辑)就不会很好,例如我想在程序被kill掉之前统计一下完成了多少的工作,这个统计类似于MapReduce,需要去每个线程获取,并且最后归并程一个统一的结果等等场景)

 

pthread_exit

此函数的使用场景是当前运行的线程运行pthread_exit得到退出,对于各个子线程能够清楚地知道自己在什么时候结束的情景下,非常好用,可是实际上往往很多时候一个线程不能知道知道在什么时候该结束,例如遭遇Ctrl+C时,kill进程时,当然如果排除所有的外界干扰的话,那就让每个线程干完自己的事情后,然后自觉地乖乖的调用pthread_exit就可以了,这并不是本文需要讨论的内容,本文的情景就是讨论如何处理特殊情况。

这里还有一种方法,既然子线程可以通过pthread_exit来正确退出,那么我们可以在遭遇Ctrl+C时,kill进程时处理signal信号,然后分别给在某一个线程可以访问的公共区域存上一个flag变量,线程内部每运行一段时间(很短)来检查一下flag,若发现需要终止自己时,自己调用pthread_exit,此法有一个弱点就是当子线程需要进行阻塞的操作时,可能无暇顾及检查flag,例如socket阻塞操作。如果你的子线程的任务基本没有非阻塞的函数,那么这么干也不失为一种很好的方案。

 

pthread_kill

不要被这个可怕的邪恶的名字所吓倒,其实pthread_kill并不像他的名字那样威力大,使用之后,你会感觉,他徒有虚名而已

pthread_kill的职责其实只是向指定的线程发送signal信号而已,并没有真正的kill掉一个线程,当然这里需要说明一下,有些信号的默认行为就是exit,那此时你使用pthread_kill发送信号给目标线程,目标线程会根据这个信号的默认行为进行操作,有可能是exit。当然我们同时也可以更改获取某个信号的行为,以此来达到我们终止子线程的目的。

 1  #define  _MULTI_THREADED
 2  #include <pthread.h>
 3  #include <stdio.h>
 4  #include <signal.h>
 5  #include  " check.h "
 6 
 7  #define  NUMTHREADS 3
 8  void  sighand( int  signo);
 9 
10  void  *threadfunc( void  *parm)
11  {
12    pthread_t             self = pthread_self();
13    pthread_id_np_t       tid;
14    int                    rc;
15 
16    pthread_getunique_np(&self, &tid);
17    printf( " Thread 0x%.8x %.8x entered\n " , tid);
18    errno =  0 ;
19    rc = sleep( 30 );
20    if  (rc !=  0  && errno == EINTR) {
21      printf( " Thread 0x%.8x %.8x got a signal delivered to it\n " ,
22             tid);
23      return  NULL;
24    }
25    printf( " Thread 0x%.8x %.8x did not get expected results! rc=%d, errno=%d\n " ,
26           tid, rc, errno);
27    return  NULL;
28  }
29 
30  int  main( int  argc,  char  **argv)
31  {
32    int                      rc;
33    int                      i;
34    struct  sigaction        actions;
35    pthread_t               threads[NUMTHREADS];
36 
37    printf( " Enter Testcase - %s\n " , argv[ 0 ]);
38  
39    printf( " Set up the alarm handler for the process\n " );
40    memset(&actions,  0 sizeof (actions));
41    sigemptyset(&actions.sa_mask);
42    actions.sa_flags =  0 ;
43    actions.sa_handler = sighand;
44 
45    rc = sigaction(SIGALRM,&actions,NULL);
46    checkResults( " sigaction\n " , rc);
47 
48    for (i= 0 ; i<NUMTHREADS; ++i) {
49      rc = pthread_create(&threads[i], NULL, threadfunc, NULL);
50      checkResults( " pthread_create()\n " , rc);
51    }
52 
53    sleep( 3 );
54    for (i= 0 ; i<NUMTHREADS; ++i) {
55      rc = pthread_kill(threads[i], SIGALRM);
56      checkResults( " pthread_kill()\n " , rc);
57    }
58 
59    for (i= 0 ; i<NUMTHREADS; ++i) {
60      rc = pthread_join(threads[i], NULL);
61      checkResults( " pthread_join()\n " , rc);
62    }
63    printf( " Main completed\n " );
64    return  0 ;
65  }
66 
67  void  sighand( int  signo)
68  {
69    pthread_t             self = pthread_self();
70    pthread_id_np_t       tid;
71  
72    pthread_getunique_np(&self, &tid);
73    printf( " Thread 0x%.8x %.8x in signal handler\n " ,
74           tid);
75    return ;
76  }

 

 运行输出为:

 1  Output:
 2 
 3  Enter Testcase - QP0WTEST/TPKILL0
 4  Set up the alarm handler  for  the process
 5  Thread  0x00000000  0000000c entered
 6  Thread  0x00000000  0000000d entered
 7  Thread  0x00000000  0000000e entered
 8  Thread  0x00000000  0000000c  in  signal handler
 9  Thread  0x00000000  0000000c got a signal delivered to it
10  Thread  0x00000000  0000000d  in  signal handler
11  Thread  0x00000000  0000000d got a signal delivered to it
12  Thread  0x00000000  0000000e  in  signal handler
13  Thread  0x00000000  0000000e got a signal delivered to it
14  Main completed

  我们可以通过截获的signal信号,来释放掉线程申请的资源,可是遗憾的是我们不能再signal处理里调用pthread_exit来终结掉线程,因为pthread_exit是中介当前线程,而signal被调用的方式可以理解为内核的回调,不是在同一个线程运行的,所以这里只能做处理释放资源的事情,线程内部只有判断有没有被中断(一般是EINTR)来断定是否要求自己结束,判定后可以调用pthread_exit退出。

   此法对于一般的操作也是非常可行的,可是在有的情况下就不是一个比较好的方法了,比如我们有一些线程在处理网络IO事件,假设它是一种一个客户端对应一个服务器线程,阻塞从Socket中读消息的情况。我们一般在网络IO的库里面回家上对EINTR信号的处理,例如recv时发现返回值小于0,检查error后,会进行他对应的操作。有可能他会再recv一次,那就相当于我的线程根本就不回终止,因为网络IO的类有可能不知道在获取EINTR时要终止线程。也就是说这不是一个特别好的可移植方案,如果你线程里的操作使用了很多外来的不太熟悉的类,而且你并不是他对EINTR的处理手段是什么,这是你在使用这样的方法来终止就有可能出问题了。而且如果你不是特别熟悉这方面的话你会很苦恼,“为什么我的测试代码全是ok的,一加入你们部门开发的框架进来就不ok了,肯定是你们框架出问题了”。好了,为了不必要的麻烦,我最后没有使用这个方案。

 

pthread_cancel

  这个方案是我最终采用的方案,我认为是解决这个问题,通用的最好的解决方案,虽然前面其他方案的有些问题他可能也不好解决,但是相比较而言,还是相当不错的

pthread_cancel可以单独使用,因为在很多系统函数里面本身就有很多的断点,当调用这些系统函数时就会命中其内部的断点来结束线程,如下面的代码中,即便注释掉我们自己设置的断点pthread_testcancel()程序还是一样的会被成功的cancel掉,因为printf函数内部有取消点(如果大家想了解更多的函数的取消点情况,可以阅读《Unix高级环境编程》的线程部分)

 1  #include <pthread.h>
 2  #include <stdio.h>
 3  #include<stdlib.h>
 4  #include <unistd.h>
 5  void  *threadfunc( void  *parm)
 6  {
 7    printf( " Entered secondary thread\n " );
 8    while  ( 1 ) {
 9      printf( " Secondary thread is looping\n " );
10      pthread_testcancel();
11      sleep( 1 );
12    }
13    return  NULL;
14  }
15 
16  int  main( int  argc,  char  **argv)
17  {
18    pthread_t             thread;
19    int                    rc= 0 ;
20 
21    printf( " Entering testcase\n " );
22 
23    /*  Create a thread using default attributes  */
24    printf( " Create thread using the NULL attributes\n " );
25    rc = pthread_create(&thread, NULL, threadfunc, NULL);
26    checkResults( " pthread_create(NULL)\n " , rc);
27 
28    /*  sleep() is not a very robust way to wait for the thread  */
29    sleep( 1 );
30 
31    printf( " Cancel the thread\n " );
32    rc = pthread_cancel(thread);
33    checkResults( " pthread_cancel()\n " , rc);
34 
35    /*  sleep() is not a very robust way to wait for the thread  */
36    sleep( 10 );
37    printf( " Main completed\n " );
38    return  0 ;
39  }

输出:

Entering testcase
Create thread  using  the NULL attributes
Entered secondary thread
Secondary thread  is  looping
Cancel the thread
Main completed

    POSIX保证了绝大部分的系统调用函数内部有取消点,我们看到很多在cancel调用的情景下,recv和send函数最后都会设置pthread_testcancel()取消点,其实这不是那么有必要的,那么究竟什么时候该pthread_testcancel()出场呢?《Unix高级环境编程》也说了,当遇到大量的基础计算时(如科学计算),需要自己来设置取消点。

ok,得益于pthread_cancel,我们很轻松的把线程可以cancel掉,可是我们的资源呢?何时释放...

下面来看两个pthread函数

1.void pthread_cleanup_push(void (*routine)(void *), void *arg); 
2.void pthread_cleanup_pop(int execute); 

这两个函数能够保证在 1函数调用之后,2函数调用之前的任何形式的线程结束调用向pthread_cleanup_push注册的回调函数
另外我们还可通过下面这个函数来设置一些状态

 int pthread_setcanceltype(int type, int *oldtype); 

CancelabilityCancelability StateCancelability Type
disabledPTHREAD_CANCEL_DISABLEPTHREAD_CANCEL_DEFERRED
disabledPTHREAD_CANCEL_DISABLEPTHREAD_CANCEL_ASYNCHRONOUS
deferredPTHREAD_CANCEL_ENABLEPTHREAD_CANCEL_DEFERRED
asynchronousPTHREAD_CANCEL_ENABLEPTHREAD_CANCEL_ASYNCHRONOUS

  当我们设置type为PTHREAD_CANCEL_ASYNCHRONOUS时,线程并不会等待命中取消点才结束,而是立马结束

  好了,下面贴代码:

 1   #include <pthread.h>                                                            
 2  #include <stdio.h>                                                              
 3  #include <stdlib.h>                                                             
 4  #include <unistd.h>                                                             
 5  #include <errno.h>                                                                                
 6  int  footprint= 0 ;
 7  char  *storage; 
 8  void  freerc( void  *s)
 9  {
10     free(s);
11     puts( " the free called " );    
12  }                                                               
13 
14  static  void  checkResults( char  * string int  rc) {
15    if  (rc) {
16      printf( " Error on : %s, rc=%d " ,
17             string , rc);
18      exit(EXIT_FAILURE);
19    }
20    return ;
21  }
22                                                                                 
23  void  *thread( void  *arg) {                                                                                                                    
24    int            rc= 0 , oldState= 0
25    rc = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState);    // close the cancel switch   
26    checkResults( " pthread_setcancelstate()\n " , rc);                                                                        
27    if  ((storage = ( char *) malloc( 80 )) == NULL) {                                 
28      perror( " malloc() failed " );                                                  
29      exit( 6 );                                                                    
30    }                                                                             
31     rc = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&oldState);    // open the cancel  switch                                                                        
32     checkResults( " pthread_setcancelstate(2)\n " , rc);  
33  /*  Plan to release storage even if thread doesn't exit normally  */            
34                                                                                 
35    pthread_cleanup_push(freerc, storage);    /* the free is method here   you can use your own method here */                                       
36                                                                                 
37    puts( " thread has obtained storage and is waiting to be cancelled " );           
38    footprint++;                                                                  
39    while  ( 1 )
40      {      
41           pthread_testcancel();    // make a break point here     
42              // pthread_exit(NULL);     // test exit to exam whether the freerc method called                                                     
43              sleep( 1 );  
44      }                                                                 
45                                                                                 
46    pthread_cleanup_pop( 1 );                                                       
47  }                                                                               
48                                                                                 
49  main() {                                                                        
50    pthread_t thid; 
51   void                  *status=NULL;                                                              
52                                                                                 
53    if  (pthread_create(&thid, NULL, thread, NULL) !=  0 ) {                         
54      perror( " pthread_create() error " );                                           
55      exit( 1 );                                                                    
56    }                                                                             
57                                                                                 
58    while  (footprint ==  0 )                                                        
59      sleep( 1 );                                                                   
60                                                                                 
61    puts( " IPT is cancelling thread " );                                             
62                                                                                 
63    if  (pthread_cancel(thid) !=  0 ) {                                              
64      perror( " pthread_cancel() error " );   
65      sleep( 2 );                                        
66      exit( 3 );                                                                    
67    }                                                                             
68                                                                                 
69    if  (pthread_join(thid, &status) !=  0 ) {  
70      if (status != PTHREAD_CANCELED){                                      
71          perror( " pthread_join() error " );                                             
72          exit( 4 );
73      }                                                                    
74    }
75   if (status == PTHREAD_CANCELED)
76      puts( " PTHREAD_CANCELED " );
77      
78   puts( " main exit " );                                                                        
79  } 

 

转载于:https://www.cnblogs.com/Creator/archive/2012/03/21/2408413.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值