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 */
  • 相关阅读:
    VS扩展开发 二 从示例程序出发
    VS扩展开发 一 导航
    CLR笔记 二 函数调用
    使用C#调用C++类库
    C#编程常用工具总结
    CLR笔记 一 概述
    C#工程中 使用targets和props实例
    VS C++工程的静态库引用问题
    C#高级编程笔记(三)
    (转)如何让CPU的使用率一直在50%
  • 原文地址:https://www.cnblogs.com/zhangshenghui/p/8947432.html
Copyright © 2011-2022 走看看