本文共 2420 字,大约阅读时间需要 8 分钟。
#include <stdio.h> #include <pthread.h> #include <signal.h> pthread_t tid1,tid2,tid_sig; pthread_cond_t cond1,cond2; pthread_mutex_t mutex1,mutex2; unsigned int flag1,flag2; unsigned long thread1_sig_counter=0; unsigned long thread2_sig_counter=0; void *thread1_func(void *arg) { sigset_t sigset; //block SIGRTMIN sigemptyset(&sigset); sigaddset(&sigset,SIGRTMIN); pthread_sigmask(SIG_SETMASK,&sigset,NULL); while(1) { pthread_mutex_lock(&mutex1); while(!flag1) { pthread_cond_wait(&cond1,&mutex1); } printf("thread1_func got signal! CNT=%ld\n",thread1_sig_counter++); //reset. flag1=0; pthread_mutex_unlock(&mutex1); } } void *thread2_func(void *arg) { sigset_t sigset; //block SIGRTMIN sigemptyset(&sigset); sigaddset(&sigset,SIGRTMIN); pthread_sigmask(SIG_SETMASK,&sigset,NULL); while(1) { pthread_mutex_lock(&mutex2); while(!flag2) { pthread_cond_wait(&cond2,&mutex2); } printf("thread2_func got signal! CNT=%ld\n",thread2_sig_counter++); //reset.here we set the flag ,it will be waken up by other thread. flag2=0; pthread_mutex_unlock(&mutex2); } } void *thread_signal(void *arg) { int ret; sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset,SIGRTMIN); while(1) { printf("thread signal:wait signal...\n"); if(0==sigwait(&sigset,&ret)) { if(SIGRTMIN==ret) { printf("trigger thread1!\n"); //trigger thread1. pthread_mutex_lock(&mutex1); flag1=1; pthread_cond_signal(&cond1); pthread_mutex_unlock(&mutex1); printf("trigger thread2!\n"); //trigger thread1. pthread_mutex_lock(&mutex2); flag2=1; pthread_cond_signal(&cond2); pthread_mutex_unlock(&mutex2); } } } } //main process. int main(void) { sigset_t sigset; pthread_mutex_init(&mutex1,NULL); pthread_mutex_init(&mutex2,NULL); pthread_cond_init(&cond1,NULL); pthread_cond_init(&cond2,NULL); flag1=flag2=0; //block SIGRTMIN sigemptyset(&sigset); sigaddset(&sigset,SIGRTMIN); pthread_sigmask(SIG_SETMASK,&sigset,NULL); if(pthread_create(&tid1,NULL,thread1_func,NULL)) { printf("create thread1 failed!\n"); return -1; } if(pthread_create(&tid2,NULL,thread2_func,NULL)) { printf("create thread2 failed!\n"); return -1; } if(pthread_create(&tid_sig,NULL,thread_signal,NULL)) { printf("create signal thread failed!\n"); return -1; } pthread_join(tid1,NULL); pthread_join(tid2,NULL); pthread_join(tid_sig,NULL); pthread_cond_destroy(&cond1); pthread_cond_destroy(&cond2); pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); printf("done!\n"); return 0; }转载地址:http://ozzji.baihongyu.com/