首页 > 代码库 > 还以为线程没运行不运行
还以为线程没运行不运行
图片是转载的,来源不清楚了。
#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确实加了换行符。但结果没出来。改动之后,没加换行。这是有多坑。
总结,对条件的理解是对的,互斥量理解也是对的,结束条件没考虑好。失败。
还以为线程没运行不运行
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。