码迷,mamicode.com
首页 > 编程语言 > 详细

(二十九)线程间信号量

时间:2018-04-26 01:19:28      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:cond   att   detach   cti   handler   unsigned   switch   for   its   

#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 */

 

(二十九)线程间信号量

标签:cond   att   detach   cti   handler   unsigned   switch   for   its   

原文地址:https://www.cnblogs.com/zhangshenghui/p/8947432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!