1 /* Copyright (c) 2002-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 /* Simple producer/consumer example with pthreads and semaphores */
15 int AmountProduced = 3; /* Amount of items produced by a producer */
16 int AmountConsumed = 3; /* Amount of items consumed by a consumer */
17 int ProducerCount = 2; /* Amount of producer threads*/
18 int ConsumerCount = 2; /* Amount of consumer threads*/
19 int BufferSize = 4; /* Size of the buffer */
26 pthread_mutex_t mutex;
29 static void* producer(void* id)
31 for (int i = 0; i < AmountProduced; i++) {
33 pthread_mutex_lock(&mutex);
36 fprintf(stderr, "Producer %d: Insert Item %d at %d\n", *((int*)id), buffer[in], in);
37 in = (in + 1) % BufferSize;
38 pthread_mutex_unlock(&mutex);
43 static void* consumer(void* id)
45 for (int i = 0; i < AmountConsumed; i++) {
47 pthread_mutex_lock(&mutex);
48 int item = buffer[out];
50 fprintf(stderr, "Consumer %d: Remove Item %d from %d\n", *((int*)id), item, out);
51 out = (out + 1) % BufferSize;
52 pthread_mutex_unlock(&mutex);
58 int main(int argc, char** argv)
61 while ((opt = getopt(argc, argv, "c:C:p:P:q")) != -1) {
67 AmountConsumed = atoi(optarg);
70 ConsumerCount = atoi(optarg);
73 AmountProduced = atoi(optarg);
76 ProducerCount = atoi(optarg);
79 printf("unknown option: %c\n", optopt);
83 pthread_t* pro = malloc(ProducerCount * sizeof(pthread_t));
84 pthread_t* con = malloc(ConsumerCount * sizeof(pthread_t));
85 buffer = malloc(sizeof(int) * BufferSize);
86 pthread_mutex_init(&mutex, NULL);
87 sem_init(&empty, 0, BufferSize);
88 sem_init(&full, 0, 0);
90 int* ids = malloc(sizeof(int) * (ProducerCount + ConsumerCount));
91 for (int i = 0; i < ProducerCount + ConsumerCount; i++)
92 ids[i] = i + 1; // The identity of each thread (for debug messages)
94 for (int i = 0; i < ProducerCount; i++)
95 pthread_create(&pro[i], NULL, producer, &ids[i]);
96 for (int i = 0; i < ConsumerCount; i++)
97 pthread_create(&con[i], NULL, consumer, &ids[i]);
99 for (int i = 0; i < ProducerCount; i++)
100 pthread_join(pro[i], NULL);
101 for (int i = 0; i < ConsumerCount; i++)
102 pthread_join(con[i], NULL);
104 pthread_mutex_destroy(&mutex);