pthread多线程模式下的信号处理机制(sigwait)及示例

目录

1. sigwait函数

2. pthread_sigmask函数

3. pthread_kill函数

4. 调用sigwait同步等待的信号必须在调用线程中被屏蔽

5. 代码示例


 

在Linux的多线程中使用信号机制,与在进程中使用信号机制有着根本的区别,可以说是完全不同。在进程环境中,对信号的处理是,先注册信号处理函数,当信号异步发生时,调用处理函数来处理信号。它完全是异步的(我们完全不知到信号会在进程的那个执行点到来!)。然而信号处理函数的实现,有着许多的限制;比如有一些函数不能在信号处理函数中调用;再比如一些函数read、recv等调用时会被异步的信号给中断(interrupt),因此我们必须对在这些函数在调用时因为信号而中断的情况进行处理(判断函数返回时 enno 是否等于 EINTR)。


但是在多线程中处理信号的原则却完全不同,它的基本原则是:将对信号的异步处理,转换成同步处理,也就是说用一个线程专门的来“同步等待”信号的到来,而其它的线程可以完全不被该信号中断/打断(interrupt)。这样就在相当程度上简化了在多线程环境中对信号的处理。而且可以保证其它的线程不受信号的影响。这样我们对信号就可以完全预测,因为它不再是异步的,而是同步的(我们完全知道信号会在哪个线程中的哪个执行点到来而被处理!)。而同步的编程模式总是比异步的编程模式简单。其实多线程相比于多进程的其中一个优点就是:多线程可以将进程中异步的东西转换成同步的来处理。

1. sigwait函数

sigwait - wait for a signal

#include <signal.h>
int sigwait(const sigset_t *set, int *sig);

从上面的man sigwait的描述中,我们知道:sigwait是同步的等待信号的到来,而不是像进程中那样是异步的等待信号的到来。sigwait函数使用一个信号集作为他的参数,并且在集合中的任一个信号发生时返回该信号值,解除阻塞,然后可以针对该信号进行一些相应的处理。

在多线程代码中,总是使用sigwait或者sigwaitinfo或者sigtimedwait等函数来处理信号。而不是signal或者sigaction等函数。因为在一个线程中调用signal或者sigaction等函数会改变所以线程中的信号处理函数。而不是仅仅改变调用signal/sigaction的那个线程的信号处理函数。


2. pthread_sigmask函数

每个线程均有自己的信号屏蔽集(信号掩码),可以使用pthread_sigmask函数来屏蔽某个线程对某些信号的响应处理,仅留下需要处理该信号的线程来处理指定的信号。实现方式是:利用线程信号屏蔽集的继承关系(在主进程中对sigmask进行设置后,主进程创建出来的线程将继承主进程的掩码)

#include <signal.h>
int pthread_sigmask(inthow, const sigset_t *set, sigset_t *oldset);

 

3. pthread_kill函数

在多线程程序中,一个线程可以使用pthread_kill对同一个进程中指定的线程(包括自己)发送信号。注意在多线程中一般不使用kill函数发送信号,因为kill是对进程发送信号,结果是:正在运行的线程会处理该信号,如果该线程没有注册信号处理函数,那么会导致整个进程退出。

#include <signal.h>
int pthread_kill(pthread_tthread, intsig);


4. 调用sigwait同步等待的信号必须在调用线程中被屏蔽

最好在所有的线程中被屏蔽,这样可以保证信号绝不会被送到除了调用sigwait的任何其它线程,这是通过利用信号掩码的继承关系来达到的。


5. 代码示例

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

/* Simpleerror handling functions*/

#define handle_error_en(en, msg)\
        do { errno= en; perror(msg);exit(EXIT_FAILURE);}while(0)

static void * sig_thread(void*arg)
{
      sigset_t *set=(sigset_t*) arg;
      int s, sig;

      for (;;){
            s = sigwait(set,&sig);
            if (s != 0)
                  handle_error_en(s,"sigwait");
            printf("Signal handling thread got signal %d\n", sig);
      }
}

int main(int argc, char*argv[])
{
      pthread_t thread;
      sigset_t set;
      int s;

      /* 
         Block SIGINT; other threads created by main() will inherit
         a copy of the signal mask. 
       */
      sigemptyset(&set);
      sigaddset(&set, SIGQUIT);
      sigaddset(&set, SIGALRM);
      s = pthread_sigmask(SIG_BLOCK,&set,NULL);
      if (s!= 0)
            handle_error_en(s,"pthread_sigmask");
      s = pthread_create(&thread,NULL,&sig_thread,(void*)&set);
      if (s!= 0)
            handle_error_en(s,"pthread_create");
      /* 
        Main thread carries on to create other threads and/ordo
        other work 
       */
      pause();/* Dummy pause so we can test program*/
      return 0;
}


编译运行情况:

这个例子演示了:通过在主线程中阻塞一些信号,其它的线程会继承信号掩码,然后专门用一个线程使用sigwait函数来同步的处理信号,使其它的线程不受到信号的影响。

#include <pthread.h>
#include <stdio.h>
#include <sys/signal.h>
#define NUMTHREADS 3
void sighand(int signo);
void *threadfunc(void *parm)
{
    pthread_t             tid = pthread_self();
    int                   rc;
    printf("Thread %u entered\n", tid);
    rc = sleep(3);
    printf("Thread %u did not get expected results! rc=%d\n", tid, rc);
    return NULL;
}
void *threadmasked(void *parm)
{
    pthread_t             tid = pthread_self();
    sigset_t              mask;
    int                   rc;
    printf("Masked thread %lu entered\n", tid);
    sigfillset(&mask); /* Mask all allowed signals */
//    sigemptyset(&mask);
    rc = pthread_sigmask(SIG_BLOCK, &mask, NULL);
    if (rc != 0)
    {
        printf("%d, %s\n", rc, strerror(rc));
        return NULL;
    }
    rc = sleep(1);
    if (rc != 0)
    {
        printf("Masked thread %lu did not get expected results! ""rc=%d \n",tid, rc);
        return NULL;
    }
//    sigwait(&mask,&rc);
    printf("Masked thread %lu completed masked work\n",tid);
    return NULL;
}
int main(int argc, char **argv)
{
    int                     rc;
    int                     i;
    struct sigaction        actions;
    pthread_t               threads[NUMTHREADS];
    pthread_t               maskedthreads[NUMTHREADS];
    printf("Enter Testcase - %s\n", argv[0]);
    printf("Set up the alarm handler for the process\n");
    memset(&actions, 0, sizeof(actions));
    sigemptyset(&actions.sa_mask);
    actions.sa_flags = 0;
    actions.sa_handler = sighand;
    rc = sigaction(SIGALRM,&actions,NULL);
    printf("Create masked and unmasked threads\n");
    for(i=0; i<NUMTHREADS; ++i)
    {
        rc = pthread_create(&threads[i], NULL, threadfunc, NULL);
        if (rc != 0)
        {
            printf("%d, %s\n", rc, strerror(rc));
            return -1;
        }
        rc = pthread_create(&maskedthreads[i], NULL, threadmasked, NULL);
        if (rc != 0)
        {
            printf("%d, %s\n", rc, strerror(rc));
            return -1;
        }
    }
    sleep(5);
    printf("Send a signal to masked and unmasked threads\n");
    for(i=0; i<NUMTHREADS; ++i)
    {
        rc = pthread_kill(threads[i], SIGALRM);
        rc = pthread_kill(maskedthreads[i], SIGALRM);
    }
    printf("Wait for masked and unmasked threads to complete\n");
    for(i=0; i<NUMTHREADS; ++i) {
        rc = pthread_join(threads[i], NULL);
        rc = pthread_join(maskedthreads[i], NULL);
    }
    printf("Main completed\n");
    return 0;
}
void sighand(int signo)
{
    pthread_t             tid = pthread_self();
    printf("Thread %lu in signal handler\n",tid);
    return;
 
}


由上面可知,线程中的信号处理机制和进程中的信号处理机制是不同的,或者说是完全不同的,一般在多线程中使用信号的,或单独启动一个线程类处理信号,在主进程中发送信号,在主进程中使用了pthread_mask()函数来处理信号屏蔽信息,这个时候在主进程中使用kill,这个时候线程也是可以接受到信号的原因是pthread_mask继承了主进程的信号屏蔽信息,这个时候也是可以在使用pthread_kill给相应的线程发送相应的信号,但是在有的程序中,在线程中使用pthread_mask,这个使用就必须使用pthread_kill来发送信号了;但是在进程中的信号机制没有这么复杂,进程中只需要注册一个函数,就静静的等待信号处理。不过在进程中使用的方法也是可以在线程中使用的。
 

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值