设为首页 加入收藏

TOP

多线程对信号的接受处理
2015-07-20 17:44:52 来源: 作者: 【 】 浏览:3
Tags:线程 信号 接受 处理

最近刚从linux C转做android,老大突然看着我闲,叫我去验证一下“一个进程有多个子线程,子线程都注册监听某个信号,另一个进程向它发送该信号的时候,它会怎么处理?”。

带着这个问题,我搜索了各个贴子之后,大概得出:

进程处理信号,你需要注册signal的一个处理函数,线程你需要用signal_wait去等待一个信号。大体得出,如果一个多线程的进程得到了信号,它是会在它诸多子线程里面选一个来执行,有人说是正在进行的那个线程。在多线程环境下,一般会让其他子线程不处理信号,专门用一个线程来处理信号,把异步变成同步处理。


光看人家的贴子是不行的的。为此,我写了如下代码来验证:

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        #include 
       
         static pthread_t g_thread_ids[2]={0}; void ouch1(int sig) { printf("mainthread interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void ouch2(int sig) { printf("child thread 1 interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void ouch3(int sig) { printf("child thread 2 interrupted,thread id:%u\n",(unsigned int)pthread_self()); //signal(SIGINT,SIG_DFL); } void thread_loop1(char* msg) { printf("child thread 1 signal now \n"); signal(SIGINT,ouch2); printf("chilid thread1:%d,%s",(int)getpid(),msg); while(1); } void thread_loop2(char* msg) { printf("child thread 2 signal now\n"); signal(SIGINT,ouch3); printf("child thread2:%d,%s",(int)getpid(),msg); while(1); } void thread_wait2() { //waiting for thread terminate if(g_thread_ids[0]!=0) { pthread_join(g_thread_ids[0],NULL); printf("thread %d terminated\n",getpid()); } if(g_thread_ids[1]!=0) { pthread_join(g_thread_ids[1],NULL); printf("thread %d terminated\n",getpid()); } } //=============test multi-thread test. void start_test() { pthread_t thread1,thread2; char *msg1="this is thread 1\n"; char *msg2="this is thread 2\n"; printf("main thread signal now\n"); signal(SIGINT,ouch1); printf("main thread signal now\n"); pthread_create(&thread1,NULL,(void*)thread_loop1,(void*)msg1); g_thread_ids[0]=thread1; pthread_create(&thread2,NULL,(void*)thread_loop2,(void*)msg2); g_thread_ids[1]=thread2; thread_wait2(); printf("all thread finished its tasks\n"); return ; } int main() { start_test(); return 0; }
       
      
     
    
   
  

上述代码的输出是,谁最后调用signal,谁就会一直处理该信号。

说明,跟正在执行的线程没关系,指定一个之后就会一直由它来处理。如果对一个信号注册了多次,那么最后一次有效,其他的都无效。

mark一下。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Leetcode 二分查找 Search a 2D M.. 下一篇C++之------运算符重载

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·MySQL 安装及连接-腾 (2025-12-25 06:20:28)
·MySQL的下载、安装、 (2025-12-25 06:20:26)
·MySQL 中文网:探索 (2025-12-25 06:20:23)
·Shell脚本:Linux Sh (2025-12-25 05:50:11)
·VMware虚拟机安装Lin (2025-12-25 05:50:08)