zoukankan      html  css  js  c++  java
  • (二十九)线程间信号量

    #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
    ", (unsigned int)tid1);
    
       millisleep(1000);     /* for some reason a sleep is needed here */
    
       for( ; ;)
       {
            //printf("main(%u) sending SIGINT to TID(%u)
    ", (unsigned int)pthread_self(), (unsigned int)tid1);
            pthread_kill(tid1, SIGUSR1);          /* not blocked by tid1 */
            
            sleep(1);
       }
    
       printf("main(%u) is exit
    ", (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)
    ", __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)
    ", (unsigned int)pthread_self());
    }  /* int_handler */
  • 相关阅读:
    计算机网络拓扑结构
    中继器,集线器,网桥,交换机,路由器
    网络层次模型
    广播域和冲突域
    Tomcat
    Log4j
    Eclipse实用快捷键
    WebService是什么?
    定时任务处理-Quartz
    MySQL内存表-临时表
  • 原文地址:https://www.cnblogs.com/zhangshenghui/p/8947432.html
Copyright © 2011-2022 走看看