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);
49 int item = buffer[out];
50 fprintf(stderr, "Consumer %d: Remove Item %d from %d\n", *((int*)id), item, out);
52 out = (out + 1) % BufferSize;
53 pthread_mutex_unlock(&mutex);
59 int main(int argc, char** argv)
62 while ((opt = getopt(argc, argv, "c:C:p:P:q")) != -1) {
68 AmountConsumed = atoi(optarg);
71 ConsumerCount = atoi(optarg);
74 AmountProduced = atoi(optarg);
77 ProducerCount = atoi(optarg);
80 printf("unknown option: %c\n", optopt);
84 pthread_t* pro = malloc(ProducerCount * sizeof(pthread_t));
85 pthread_t* con = malloc(ConsumerCount * sizeof(pthread_t));
86 buffer = malloc(sizeof(int) * BufferSize);
87 pthread_mutex_init(&mutex, NULL);
88 sem_init(&empty, 0, BufferSize);
89 sem_init(&full, 0, 0);
91 int* ids = malloc(sizeof(int) * (ProducerCount + ConsumerCount));
92 for (int i = 0; i < ProducerCount + ConsumerCount; i++)
93 ids[i] = i + 1; // The identity of each thread (for debug messages)
95 for (int i = 0; i < ProducerCount; i++)
96 pthread_create(&pro[i], NULL, producer, &ids[i]);
97 for (int i = 0; i < ConsumerCount; i++)
98 pthread_create(&con[i], NULL, consumer, &ids[i]);
100 for (int i = 0; i < ProducerCount; i++)
101 pthread_join(pro[i], NULL);
102 for (int i = 0; i < ConsumerCount; i++)
103 pthread_join(con[i], NULL);
105 pthread_mutex_destroy(&mutex);