- 论坛徽章:
- 0
|
APUE当中,第12章线程控制,335页。为什么首先在主线程当中,先可以被锁一次,然后在子线程当中又可以被锁住一次- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <stdio.h>
- #include <signal.h>
- int quitflag = 0;
- sigset_t mask;
- pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
- void * thr_dn(void *arg)
- {
- int err,signo;
- while(1)
- {
- err = sigwait(&mask, &signo);
- if(err != 0)
- printf("sigwait fail\n");
- switch(signo)
- {
- case SIGINT :
- printf("get sigint \n");
- break;
- case SIGQUIT :
- printf("get sigquit\n");
- pthread_mutex_lock(&lock);
- printf("child thread get lock\n");
- quitflag = 1;
- pthread_mutex_unlock(&lock);
- printf("child thread unlock\n");
- pthread_cond_signal(&wait);
- return (0);
- default :
- printf("get unexpected %d\n", signo);
- exit(1);
- }
- }
- }
- int main()
- {
- int err;
- sigset_t oldmask;
- pthread_t tid;
- sigemptyset(&mask);
- sigaddset(&mask, SIGINT);
- sigaddset(&mask, SIGQUIT);
- if(err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask) != 0)
- {
- printf("SIGBLOCK ERROR\n");
- }
- if(err = pthread_create(&tid, NULL, thr_dn, 0))
- {
- printf("create thread error");
- }
- pthread_mutex_lock(&lock);
- printf("main thread get lock\n");
- while(quitflag == 0)
- {
- pthread_cond_wait(&wait, &lock);
- printf("cond wait quit\n");
- }
- pthread_mutex_unlock(&lock);
- printf("main thread unlock\n");
- return 0;
- }
复制代码 |
|