如题所述:
子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
之前编程用到pthread_cond_init没用调用相应destroy,程序执行完毕后也没core掉,在网上找了找原因,最终确定在linux的实现原理。
说白了,linux下可以不调用。但为了健壮性,还是要用配套的destroy.
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <pthread.h> 5 #include <errno.h> 6 7 8 9 pthread_cond_t cond_child; 10 pthread_cond_t cond_father; 11 12 pthread_mutex_t mf; 13 14 15 void *thread_child(void *arg) 16 { 17 int i,j,k; 18 for(i = 0; i < 50; i++) 19 { 20 for(j = 0; j < 2; j++) 21 { 22 if(pthread_mutex_lock(&mf)!= 0) 23 { 24 pthread_exit(NULL); 25 } 26 for(k = 0; k < 10; k++) 27 printf("child is here[%d]\n", k); 28 pthread_cond_signal(&cond_father); 29 if(pthread_cond_wait(&cond_child, &mf) != 0) 30 { 31 pthread_exit(NULL); 32 } 33 34 if(pthread_mutex_unlock(&mf)!= 0) 35 { 36 pthread_exit(NULL); 37 } 38 } 39 } 40 } 41 42 43 int main(int argc, char *argv[]) 44 { 45 46 pthread_t child; 47 int ret; 48 pthread_cond_init(&cond_child, NULL); 49 50 pthread_cond_init(&cond_father, NULL); 51 //pthread_mutex_init(&mc, NULL); 52 pthread_mutex_init(&mf, NULL); 53 54 55 ret = pthread_create(&child, NULL, thread_child, (void*)2); 56 if(ret) 57 { 58 return 1; 59 } 60 61 int i,j,k; 62 for(i = 0; i < 50; i++) 63 { 64 for(j = 0; j < 2; j++) 65 { 66 if(pthread_mutex_lock(&mf)!= 0) 67 { 68 pthread_exit(NULL); 69 } 70 71 if(pthread_cond_wait(&cond_father, &mf) != 0) 72 { 73 pthread_exit(NULL); 74 } 75 for(k = 0; k < 100; k++) 76 printf("father is here[%d]\n", k); 77 pthread_cond_signal(&cond_child); 78 79 if(pthread_mutex_unlock(&mf)!= 0) 80 { 81 pthread_exit(NULL); 82 } 83 //printf("other 100 cycle begin[%d]\n", i); 84 85 } 86 87 } 88 pthread_join(child, NULL); 89 pthread_cond_destroy(&cond_father); 90 pthread_cond_destroy(&cond_child); 91 pthread_mutex_destroy(&mf); 92 93 printf("main thread exit\n"); 94 return 0; 95 }
浙公网安备 33010602011771号