1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<unistd.h> 5 #include<pthread.h> 6 pthread_mutex_t mutex_x = PTHREAD_MUTEX_INITIALIZER; 7 int total_ticket_num = 20; 8 void *sell_ticket(void *arg) { 9 for (int i = 0; i < 20; i++) { 10 pthread_mutex_lock(&mutex_x); 11 if (total_ticket_num > 0) { 12 sleep(1); 13 printf("sell the %dth ticket ", 21 - total_ticket_num); 14 total_ticket_num--; 15 } 16 pthread_mutex_unlock(&mutex_x); 17 } 18 return 0; 19 } 20 int main() { 21 int iRet; 22 pthread_t tids[4]; 23 int i = 0; for (i = 0; i < 4; i++) { 24 int iRet = pthread_create(&tids[i], NULL, &sell_ticket, NULL); 25 if (iRet) { 26 printf("pthread_create error, iRet=%d ", iRet); 27 return iRet; 28 } 29 } 30 sleep(30); 31 void *retval; 32 for (i = 0; i < 4; i++) { 33 iRet = pthread_join(tids[i], &retval); 34 if (iRet) { 35 printf("tid = %d,join error, iRet=%d ",tids[i], iRet); 36 return iRet; 37 } 38 printf("retval = %ld ", (long*)retval); 39 } 40 return 0; 41 }