当某一个线程在等待一个条件变量时候会自动释放掉所占用的资源,以便不影响其他线程的抢占,等待一个条件信号需要不断进行判断,即需要在一个while条件循环中进行,不然会很难等到条件信号。 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<pthread.h> #include<semaphore.h> pthread_cond_t t1_ok,t2_ok; pthread_mutex_t lock; int t1_done=0; int t2_done=0; void *thread1(void *arg) { pthread_mutex_lock(&lock); printf("in thread 1\n"); while(!t2_done) { printf("waiting for thread 2 done\n"); pthread_cond_wait(&t2_ok,&lock); printf("t1 wait done\n"); break; } t1_done=1; pthread_mutex_unlock(&lock); return NULL; } void *thread2(void *arg) { pthread_mutex_lock(&lock); printf("in thread 2\n"); while(!t1_done) { printf("waiting for thread 1 done\n"); pthread_cond_signal(&t2_ok); pthread_mutex_unlock(&lock); usleep(10); pthread_mutex_lock(&lock); } printf("t2 wait done\n"); pthread_mutex_unlock(&lock); return NULL; } void *thread3(void *arg) { pthread_mutex_lock(&lock); printf("in thread 3\n"); pthread_mutex_unlock(&lock); return NULL; } void *thread4(void *arg) { pthread_mutex_lock(&lock); printf("in thread 4\n"); pthread_mutex_unlock(&lock); return NULL; } int main(void) { int ret; void *val; pthread_t t1,t2,t3,t4; pthread_mutex_init(&lock,NULL); pthread_cond_init(&t1_ok,NULL); ret = pthread_create(&t1,NULL,thread1,NULL); if(ret==-1) { printf("create thread1 error\n"); exit(1); } ret = pthread_create(&t2,NULL,thread2,NULL); if(ret==-1) { printf("create thread2 error\n"); exit(1); } ret = pthread_create(&t3,NULL,thread3,NULL); if(ret==-1) { printf("create thread3 error\n"); exit(1); } ret = pthread_create(&t4,NULL,thread4,NULL); if(ret==-1) { printf("create thread4 error\n"); exit(1); } pthread_join(t1,&val); pthread_join(t2,&val); pthread_join(t3,&val); pthread_join(t4,&val); pthread_mutex_destroy(&lock); pthread_cond_destroy(&t1_ok); exit(0); } 运行结果: 可以看到线程先后顺序是随机的,并且等待过程没有阻塞其他线程,而只是阻塞自身线程,并继续不断等待条件信号。 |
|
来自: champion_xu > 《my yc》