- 論壇徽章:
- 0
|
我想做一個(gè)程序的效果是線程在得到主控制的進(jìn)程發(fā)出的信號(hào)的時(shí)候才會(huì)運(yùn)行,但是在運(yùn)行的時(shí)候發(fā)現(xiàn)線程注冊(cè)的信號(hào)回調(diào)函數(shù)不能工作,我看書(shū)上說(shuō)的線程本質(zhì)也是輕量的進(jìn)程,而且本身也有信號(hào)處理機(jī)制。但是這個(gè)信號(hào)回調(diào)函數(shù)為何沒(méi)有反應(yīng)?
程序如下
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <string.h>
- #include <unistd.h>
- #include <signal.h>
- #include <errno.h>
- /**
- * 搭建一個(gè)線程,開(kāi)始阻塞,然后
- * 遇到一個(gè)信號(hào)后解除阻塞,開(kāi)始
- * 工作
- */
- //線程控制結(jié)構(gòu)體
- 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;
- //安裝一個(gè)信號(hào)處理函數(shù)
- signal(PTHREAD_ON_SIG,pth_on);//開(kāi)啟線程信號(hào)處理函數(shù)
- //線程的異步信號(hào)只接收指定信號(hào)集給定的信號(hào)
- sigset_t p_func_sig;
- sigemptyset(&p_func_sig);//初始化一個(gè)空信號(hào)集
- sigaddset(&p_func_sig,PTHREAD_ON_SIG);//填加一個(gè)信號(hào)集
- int sig_arv;//到達(dá)的信號(hào)
- 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[])
- {
- //初始化這個(gè)控制結(jié)構(gòu)體
- 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;
- }
- //注冊(cè)一個(gè)信號(hào),采用定時(shí)器的方式
- //在一定的時(shí)間向線程發(fā)送信號(hào)
- //signal(PTHREAD_CTRL_TIMER,
- while(1)
- {
- //定時(shí)器發(fā)送信號(hào)
- sleep(5);
- pthread_kill(newthid,PTHREAD_ON_SIG);
- sleep(5);
- //這里應(yīng)該使用一個(gè)互斥體
- //將控制標(biāo)志鎖住,防止影
- //響其他線程
- pthread_mutex_lock(&(p_c.num_mutex));
- p_c.flag = 1;
- pthread_mutex_unlock(&(p_c.num_mutex));
- }
- return 0;
- }
復(fù)制代碼 這個(gè)程序運(yùn)行的效果
- 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
- ....
復(fù)制代碼 這個(gè)程序運(yùn)行的時(shí)候線程等待進(jìn)程發(fā)送信號(hào),然后解除阻塞運(yùn)行,然后運(yùn)行一段時(shí)間后,主線程修改和進(jìn)程共用的一個(gè)變量然后線程重新進(jìn)入阻塞狀態(tài)。但是就是沒(méi)有發(fā)現(xiàn)主進(jìn)程發(fā)送信號(hào)的時(shí)候,線程注冊(cè)的信號(hào)函數(shù)被調(diào)用(本來(lái)應(yīng)該打印一句話)。不知道是不是使用方法沒(méi)有對(duì)??懇求指教!謝謝! |
|