- 论坛徽章:
- 0
|
我想做一个程序的效果是线程在得到主控制的进程发出的信号的时候才会运行,但是在运行的时候发现线程注册的信号回调函数不能工作,我看书上说的线程本质也是轻量的进程,而且本身也有信号处理机制。但是这个信号回调函数为何没有反应?
程序如下
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <string.h>
- #include <unistd.h>
- #include <signal.h>
- #include <errno.h>
- /**
- * 搭建一个线程,开始阻塞,然后
- * 遇到一个信号后解除阻塞,开始
- * 工作
- */
- //线程控制结构体
- typedef struct pthread_control
- {
- uint8_t flag:1;
- uint8_t flag_b:1;
- uint8_t flag_c:1;
- uint8_t flag_d:1;
- uint8_t flag_e:1;
- uint8_t flag_f:1;
- uint8_t flag_g:1;
- uint8_t flag_h:1;
- pthread_mutex_t num_mutex;
- } pth_ctrl;
- #define PTHREAD_ON_SIG SIGRTMIN+3
- #define PTHREAD_OFF_SIG SIGRTMAX-3
- void pth_on(int signo)
- {
- puts("pthread now on\n");
- }
- //线程
- void *p_func(void *arg)
- {
- uint32_t count = 0;
- pth_ctrl *p_c = (pth_ctrl *)arg;
- //安装一个信号处理函数
- signal(PTHREAD_ON_SIG,pth_on);//开启线程信号处理函数
- //线程的异步信号只接收指定信号集给定的信号
- sigset_t p_func_sig;
- sigemptyset(&p_func_sig);//初始化一个空信号集
- sigaddset(&p_func_sig,PTHREAD_ON_SIG);//填加一个信号集
- int sig_arv;//到达的信号
- uint8_t ctrl_flag;
- while(1)
- {
- pthread_mutex_lock(&(p_c->num_mutex));
- ctrl_flag = p_c->flag;
- pthread_mutex_unlock(&(p_c->num_mutex));
- if(ctrl_flag)
- {
- sigwait(&p_func_sig,&sig_arv);
- //p_c->flag = ~(p_c->flag);
- puts("thread on do what you want\n");
- ctrl_flag = !ctrl_flag;
- }
- pthread_mutex_lock(&(p_c->num_mutex));
- p_c->flag = ctrl_flag;
- pthread_mutex_unlock(&(p_c->num_mutex));
- printf("run %d times\n",count++);
- sleep(1);
- }
- }
- int main(int argc,char *argv[])
- {
- //初始化这个控制结构体
- pth_ctrl p_c;
- memset(&p_c,0,sizeof(pth_ctrl));
- p_c.flag = 1;
- //线程初始化
- pthread_t newthid;
- if(pthread_create(&newthid,NULL,p_func,&p_c) != 0)
- {
- perror("thread create failed");
- return -1;
- }
- //注册一个信号,采用定时器的方式
- //在一定的时间向线程发送信号
- //signal(PTHREAD_CTRL_TIMER,
- while(1)
- {
- //定时器发送信号
- sleep(5);
- pthread_kill(newthid,PTHREAD_ON_SIG);
- sleep(5);
- //这里应该使用一个互斥体
- //将控制标志锁住,防止影
- //响其他线程
- pthread_mutex_lock(&(p_c.num_mutex));
- p_c.flag = 1;
- pthread_mutex_unlock(&(p_c.num_mutex));
- }
- return 0;
- }
复制代码 这个程序运行的效果
- thread on do what you want
- run 0 times
- run 1 times
- run 2 times
- run 3 times
- run 4 times
- thread on do what you want
- run 5 times
- run 6 times
- run 7 times
- run 8 times
- run 9 times
- ....
复制代码 这个程序运行的时候线程等待进程发送信号,然后解除阻塞运行,然后运行一段时间后,主线程修改和进程共用的一个变量然后线程重新进入阻塞状态。但是就是没有发现主进程发送信号的时候,线程注册的信号函数被调用(本来应该打印一句话)。不知道是不是使用方法没有对??恳求指教!!谢谢!! |
|