From 5710c55d4ffe4668f688ea00ca3d54cfd4c63e73 Mon Sep 17 00:00:00 2001 From: INX Date: Wed, 26 Jul 2017 00:14:26 -0700 Subject: [PATCH] Add files via upload --- code/pthread_mutex_cond.c | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 code/pthread_mutex_cond.c diff --git a/code/pthread_mutex_cond.c b/code/pthread_mutex_cond.c new file mode 100644 index 0000000..2f7ecf2 --- /dev/null +++ b/code/pthread_mutex_cond.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include + +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t ready = PTHREAD_COND_INITIALIZER; + +int traveler_cond = 0; + +void *traveler_arrive(void *name){ + printf("traveler %s need a taxi now\n", (char *)name); + pthread_mutex_lock(&lock); + traveler_cond++; + pthread_cond_wait(&ready, &lock); + pthread_mutex_unlock(&lock); + printf("traveler %s now got a taxi\n", (char *)name); + pthread_exit((void *)0); +} + +void *taxi_arrived(void *name){ + printf("taxi %s arrives\n", (char *)name); + while(1){ + pthread_mutex_lock(&lock); + if(traveler_cond > 0){ + pthread_cond_signal(&ready); + pthread_mutex_unlock(&lock); + break; + } + pthread_mutex_unlock(&lock); + } + pthread_exit((void *)0); +} + +int main(){ + pthread_t tids[3]; + int iRet = pthread_create(&tids[0], NULL, taxi_arrived, (void *)("Jack")); + if(iRet){ + printf("pthread_create error : iRet = %d\n", iRet); + return iRet; + } + printf("time passing by\n"); + sleep(1); + iRet = pthread_create(&tids[1], NULL, traveler_arrive, (void *)("Susan")); + if(iRet){ + printf("pthread_create error : iRet = %d\n", iRet); + return iRet; + } + printf("time passing by\n"); + sleep(1); + iRet = pthread_create(&tids[0], NULL, taxi_arrived, (void *)("Mike")); + if(iRet){ + printf("pthread_create error : iRet = %d\n", iRet); + return iRet; + } + printf("time passing by\n"); + sleep(1); + void *retval; + for(int i = 0; i < 3; i++){ + iRet = pthread_join(tids[i], &retval); + if(iRet){ + printf("pthread_join error : iRet = %d\n", iRet); + return iRet; + } + printf("retval = %ld\n", (long)retval); + } + return 0; +} \ No newline at end of file