Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add more tests from McMini
[simgrid.git] / teshsuite / mc / mcmini / producer_consumer_ok.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <pthread.h>
5 #include <semaphore.h>
6
7 #define MaxBufferSize 5
8
9 sem_t empty;
10 sem_t full;
11 int in = 0;
12 int out = 0;
13 int buffer[MaxBufferSize];
14 pthread_mutex_t mutex;
15 int BufferSize;
16 int ItemCount;
17 int DEBUG;
18
19 static void *producer(void *pno)
20 {
21     int item;
22     for(int i = 0; i < ItemCount; i++) {
23         item = rand(); // Produce an random item
24         sem_wait(&empty);
25         pthread_mutex_lock(&mutex);
26         buffer[in] = item;
27         if (DEBUG) {
28           printf("Producer %d: Insert Item %d at %d\n",
29                  *((int *)pno),buffer[in],in);
30         }
31         in = (in+1)%BufferSize;
32         pthread_mutex_unlock(&mutex);
33         sem_post(&full);
34     }
35     return NULL;
36 }
37
38 static void *consumer(void *cno)
39 {
40     for(int i = 0; i < ItemCount; i++) {
41         sem_wait(&full);
42         pthread_mutex_lock(&mutex);
43         int item = buffer[out];
44         if (DEBUG) {
45           printf("Consumer %d: Remove Item %d from %d\n",
46                  *((int *)cno),item, out);
47         }
48         out = (out+1)%BufferSize;
49         pthread_mutex_unlock(&mutex);
50         sem_post(&empty);
51     }
52     return NULL;
53 }
54
55 int main(int argc, char* argv[]) 
56 {
57     if (argc < 6) {
58       printf("Usage: %s <NUM_PRODUCERS> <NUM_CONSUMERS> <ITEM_COUNT> <BUFFER_SIZE> <DEBUG>\n", argv[0]);
59       return 1;
60     }
61   
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]);
67
68     pthread_t pro[NUM_PRODUCERS],con[NUM_CONSUMERS];
69
70     pthread_mutex_init(&mutex, NULL);
71     sem_init(&empty,0,BufferSize);
72     sem_init(&full,0,0);
73
74     int a[NUM_PRODUCERS > NUM_CONSUMERS ? NUM_PRODUCERS : NUM_CONSUMERS];
75
76     for(int i = 0; i < NUM_PRODUCERS; i++) {
77         a[i] = i+1;
78         pthread_create(&pro[i], NULL, producer, (void *)&a[i]);
79     }
80     for(int i = 0; i < NUM_CONSUMERS; i++) {
81         a[i] = i+1;
82         pthread_create(&con[i], NULL, consumer, (void *)&a[i]);
83     }
84
85     for(int i = 0; i < NUM_PRODUCERS; i++) {
86         pthread_join(pro[i], NULL);
87     }
88     for(int i = 0; i < NUM_CONSUMERS; i++) {
89         pthread_join(con[i], NULL);
90     }
91
92     return 0;
93 }