(二十九)线程间信号量

#define _POSIX_C_SOURCE 199506L
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

static void int_handler(int signo);

void millisleep(int milliseconds)
{
      usleep(milliseconds * 1000);
}

main()
{
   pthread_t tid1;
   pthread_attr_t attr_obj;             /* a thread attribute variable */
   void *thread_1(void *);
   sigset_t sigmask;                 
   struct sigaction action;

   /* set up signal mask to block all in main thread */
   sigfillset(&sigmask);                /* to turn on all bits */
   pthread_sigmask(SIG_BLOCK, &sigmask, (sigset_t *)0);

   /* set up signal handlers for SIGINT & SIGUSR1 */
   action.sa_flags = 0;
   action.sa_handler = int_handler;
   sigaction(SIGUSR1, &action, (struct sigaction *)0);

   pthread_attr_init(&attr_obj);        /* init it to default */
   pthread_attr_setdetachstate(&attr_obj, PTHREAD_CREATE_DETACHED);
   pthread_create(&tid1, &attr_obj, thread_1, (void *)NULL);
   printf("TID(%u) created\n", (unsigned int)tid1);

   millisleep(1000);     /* for some reason a sleep is needed here */

   for( ; ;)
   {
        //printf("main(%u) sending SIGINT to TID(%u)\n", (unsigned int)pthread_self(), (unsigned int)tid1);
        pthread_kill(tid1, SIGUSR1);          /* not blocked by tid1 */
        
        sleep(1);
   }

   printf("main(%u) is exit\n", (unsigned int)pthread_self());
   pthread_exit((void *)NULL);          /* will not terminate process */
}  /* main */

void *thread_1(void *dummy)
{                               
   int sig;
   sigset_t sigmask;

   sigfillset(&sigmask);                /* will unblock all signals */  
   pthread_sigmask(SIG_UNBLOCK, &sigmask, (sigset_t *)0);
   for( ; ;)
   {
        sigwait(&sigmask, &sig);
        switch(sig) {
            case SIGUSR1:
                printf("%s()-%d. SIGUSR1 received by TID(%u)\n", __FUNCTION__,__LINE__,(unsigned int)pthread_self());
            break;
            default:   
            break;
        }
   }       
   
   pthread_exit((void *)NULL);          /* calling thread will terminate */
}  /* thread_1 */

static void int_handler(int dummy)
{
   //printf("SIGUSR1 received by TID(%u)\n", (unsigned int)pthread_self());
}  /* int_handler */

猜你喜欢

转载自www.cnblogs.com/zhangshenghui/p/8947432.html