标签:des style blog http color os io ar for
图片是转载的,来源不清楚了。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <errno.h> pthread_cond_t cond_a; pthread_cond_t cond_b; pthread_cond_t cond_c; pthread_mutex_t lock_a; pthread_mutex_t lock_b; pthread_mutex_t lock_c; void * funa(void *arg) { int i; for(i = 0; i<10;i++) { if ( pthread_mutex_lock(&lock_a)) { printf("lock failure\n"); exit(0); } printf("A[%d]\n", i); if ( pthread_cond_signal(&cond_b)) { printf("lock failure\n"); exit(0); } if ( pthread_cond_wait(&cond_a, &lock_a)) { printf("lock failure\n"); exit(0); } if (pthread_mutex_unlock(&lock_a)) { printf("lock failure\n"); exit(0); } } printf("A exit\n"); pthread_exit(NULL); } void * funb(void *arg) { int i; for(i = 0; i<10;i++) { if ( pthread_mutex_lock(&lock_b)) { printf("lock failure\n"); exit(0); } printf("B[%d]", i); if ( pthread_cond_signal(&cond_c)) { printf("lock failure\n"); exit(0); } if ( pthread_cond_wait(&cond_b, &lock_b)) { printf("lock failure\n"); exit(0); } if (pthread_mutex_unlock(&lock_b)) { printf("lock failure\n"); exit(0); } } printf("A exit\n"); pthread_exit(NULL); } void * func(void *arg) { int i; for(i = 0; i<10;i++) { if ( pthread_mutex_lock(&lock_c)) { printf("lock failure\n"); exit(0); } printf("C[%d]", i); if ( pthread_cond_signal(&cond_a)) { printf("lock failure\n"); exit(0); } if ( pthread_cond_wait(&cond_c, &lock_c)) { printf("lock failure\n"); exit(0); } if (pthread_mutex_unlock(&lock_c)) { printf("lock failure\n"); exit(0); } } printf("A exit\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t ta,tb,tc; int ret; int i; pthread_mutex_init(&lock_a, NULL); pthread_mutex_init(&lock_b, NULL); pthread_mutex_init(&lock_c, NULL); pthread_cond_init(&cond_a, NULL); pthread_cond_init(&cond_b, NULL); pthread_cond_init(&cond_c, NULL); ret = pthread_create(&ta, NULL, funa, (void*)1); if(ret) { printf("pthread_create ta error [%s]", strerror(errno)); return 1; } ret = pthread_create(&tb, NULL, funb, (void*)2); if(ret) { printf("pthread_create tb error [%s]", strerror(errno)); return 1; } ret = pthread_create(&tc, NULL, func, (void*)3); if(ret) { printf("pthread_create tc error [%s]", strerror(errno)); return 1; } pthread_join(ta, NULL); pthread_join(tb, NULL); pthread_join(tc, NULL); pthread_cond_destroy(&cond_a); pthread_cond_destroy(&cond_b); pthread_cond_destroy(&cond_c); pthread_mutex_destroy(&lock_a); pthread_mutex_destroy(&lock_b); pthread_mutex_destroy(&lock_c); printf("\nmain thread exit\n"); return 0; }
为什么不运行呢。保存下
----------------------------------------------------
调试了半天,不是不运行,而是有缓存,并且第10次之后,A会退出,而B与C会等待, 一直处于等待状态。看来之前自己的疑惑没问题,有问题的是没考虑结束状态。准备diy一个printf函数,这个函数太坑。之前不是没考虑有缓存的状态,但只在打印A时加了\n。晕,考虑到这,我的第一版程序是什么样也不知道了,不过A确实加了换行符。但结果没出来。改动之后,没加换行。这是有多坑。
总结,对条件的理解是对的,互斥量理解也是对的,结束条件没考虑好。失败。
标签:des style blog http color os io ar for
原文地址:http://www.cnblogs.com/boota/p/3949394.html