#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h>int ticket_cnt = 20; /* Total 20 tickets */typedef struct tag{int s_id; pthread_mutex_t *s_p;} data,*pdata;void* handler (void *arg) {int id = ((pDATA) arg)->s_id; pthread_mutex_t *p_mutex = ((PDATA) arg), s_p; printf ("A window on!:%d \ n", id); while (1) {pthread_mutex_lock (P_mutex); if (ticket_cnt = = 0) {printf ("Ticket out! \ n "); Pthread_mutex_unlock (P_mutex); Free ((PDATA) arg); Return (void*) 0; }--ticket_cnt; Sleep (rand ()%3 + 1); printf ("Window:%d:a ticket sold. Left:%d \ n ", id,ticket_cnt); Pthread_mutex_unlock (P_mutex); Sleep (rand ()% 3 + 1); /* If you do not sleep, the lock will always be occupied by this executed thread */}}int main (int argc, char *argv[]) {Srand (Getpid ()); pthread_mutex_t Mutex; Pthread_mutex_init (&mutex, NULL); int thd_cnt = atoi (argv[1]); /* Enter the number of ticket windows from the command line */PThread_t *tds = (pthread_t*) calloc (thd_cnt,sizeof (pthread_t)); int index; for (index = 0; index < thd_cnt; index++) {PDATA p = (PDATA) calloc (1,sizeof (DATA)); p->s_id = index; p->s_p = &mutex; Pthread_create (TDS + index, Null,handler, (void*) p); } printf ("joining...\n"); for (index = 0; index < thd_cnt; index++) {pthread_join (tds[index],null); } Pthread_mutex_destroy (&mutex); return 0;}
Linux multi-threaded mutex-ticketing