其次,向信号集中加入我们想等待的信号#include <signal.h>
sigset_t set;
最后,将该信号集中的信号加入到线程信号屏蔽字(线程信号等待队列)中#include <signal.h>
int sigemptyset(sigset_t *set);//清空信号集
int sigaddset(sigset_t *set,int signo);//将某个信号加入到信号集中
int sigdelset(sigset_t *set,int signo);//删除信号集中的某个信号
int sigfillset(sigset_t *set);//包含所有已定义的信号
how:#include <signal.h> int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset);
thread:给哪个线程发送信号#include <signal.h> int pthread_kill(pthread_t thread, int sig);
创建好线程后, thread1和thread2一直处于睡眠状态,当用户输入1时向thread1发送信号SIGUSR1,即被唤醒,然后完成它的事后又继续睡眠等待信号再次来到。,当用户输入2时向thread2发送信号SIGUSR1,即被唤醒,然后完成它的事后又继续睡眠等待信号再次来到。#include <stdio.h> #include <pthread.h> #include <signal.h>
void *threadfunc1(void *pvoid) { int signum; sigset_t sig; int signum; sigemptyset(&sig); sigaddset(&sig,SIGUSR1); pthread_sigmask(SIG_BLOCK,&sig,NULL);//设置该线程的信号屏蔽字为SIGUSR1 while(1) { sigwait(&sig,&signum);//睡眠等待SIGUSR1信号的到来
printf("threadfunc1 waiting is over!\n"); } } void *threadfunc2(void *pvoid) { int signum; sigset_t sig; int signum; sigemptyset(&sig); sigaddset(&sig,SIGUSR1); pthread_sigmask(SIG_BLOCK,&sig,NULL);//设置该线程的信号屏蔽字为SIGUSR1 while(1) { sigwait(&sig,&signum);//睡眠等待SIGUSR1信号的到来 printf("threadfunc2 waiting is over!\n"); } }
void main() { pthread_t thread1,thread2; pthread_create(&thread1,NULL,threadfunc1,(void *)NULL); pthread_create(&thread2,NULL,threadfunc2,(void *)NULL); pthread_detach(thread1); pthread_detach(thread2); struct sigaction act; act.sa_handler=SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags=0; sigaction(SIGUSR1,&act,0);//设置信号SIGUSR1的处理方式忽略
while(1) { printf("please input select a number in (1,2)!\n"); scanf("%d",&i); if(i==1) pthread_kill(thread1,SIGUSR1);
if(i==2) pthread_kill(thread2,SIGUSR1); } }
//编译 gcc -o pthread pthread.c -lpthread