7 #define MaxBufferSize 5
13 int buffer[MaxBufferSize];
14 pthread_mutex_t mutex;
19 static void *producer(void *pno)
22 for(int i = 0; i < ItemCount; i++) {
23 item = rand(); // Produce an random item
25 pthread_mutex_lock(&mutex);
28 printf("Producer %d: Insert Item %d at %d\n",
29 *((int *)pno),buffer[in],in);
31 in = (in+1)%BufferSize;
32 pthread_mutex_unlock(&mutex);
38 static void *consumer(void *cno)
40 for(int i = 0; i < ItemCount; i++) {
42 pthread_mutex_lock(&mutex);
43 int item = buffer[out];
45 printf("Consumer %d: Remove Item %d from %d\n",
46 *((int *)cno),item, out);
48 out = (out+1)%BufferSize;
49 pthread_mutex_unlock(&mutex);
55 int main(int argc, char* argv[])
58 printf("Usage: %s <NUM_PRODUCERS> <NUM_CONSUMERS> <ITEM_COUNT> <BUFFER_SIZE> <DEBUG>\n", argv[0]);
62 int NUM_PRODUCERS = atoi(argv[1]);
63 int NUM_CONSUMERS = atoi(argv[2]);
64 ItemCount = atoi(argv[3]);
65 BufferSize = atoi(argv[4]);
66 DEBUG = atoi(argv[5]);
68 pthread_t pro[NUM_PRODUCERS],con[NUM_CONSUMERS];
70 pthread_mutex_init(&mutex, NULL);
71 sem_init(&empty,0,BufferSize);
74 int a[NUM_PRODUCERS > NUM_CONSUMERS ? NUM_PRODUCERS : NUM_CONSUMERS];
76 for(int i = 0; i < NUM_PRODUCERS; i++) {
78 pthread_create(&pro[i], NULL, producer, (void *)&a[i]);
80 for(int i = 0; i < NUM_CONSUMERS; i++) {
82 pthread_create(&con[i], NULL, consumer, (void *)&a[i]);
85 for(int i = 0; i < NUM_PRODUCERS; i++) {
86 pthread_join(pro[i], NULL);
88 for(int i = 0; i < NUM_CONSUMERS; i++) {
89 pthread_join(con[i], NULL);