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 */
14 #define AmountProduced 3 /* Amount of items produced by a producer */
15 #define AmountConsumed 3 /* Amount of items consumed by a consumer */
16 #define ProducerCount 2 /* Amount of producer threads*/
17 #define ConsumerCount 2 /* Amount of consumer threads*/
18 #define BufferSize 4 /* Size of the buffer */
24 int buffer[BufferSize];
25 pthread_mutex_t mutex;
28 static void* producer(void* id)
30 for (int i = 0; i < AmountProduced; i++) {
32 pthread_mutex_lock(&mutex);
35 fprintf(stderr, "Producer %d: Insert Item %d at %d\n", *((int*)id), buffer[in], in);
36 in = (in + 1) % BufferSize;
37 pthread_mutex_unlock(&mutex);
42 static void* consumer(void* id)
44 for (int i = 0; i < AmountConsumed; i++) {
46 pthread_mutex_lock(&mutex);
47 int item = buffer[out];
49 fprintf(stderr, "Consumer %d: Remove Item %d from %d\n", *((int*)id), item, out);
50 out = (out + 1) % BufferSize;
51 pthread_mutex_unlock(&mutex);
57 int main(int argc, char** argv)
59 if (argc == 2 && strcmp(argv[1], "-q") == 0)
61 pthread_t pro[2], con[2];
62 pthread_mutex_init(&mutex, NULL);
63 sem_init(&empty, 0, BufferSize);
64 sem_init(&full, 0, 0);
66 int ids[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // The identity of each thread (for debug messages)
68 for (int i = 0; i < ProducerCount; i++)
69 pthread_create(&pro[i], NULL, (void*)producer, (void*)&ids[i]);
70 for (int i = 0; i < ConsumerCount; i++)
71 pthread_create(&con[i], NULL, (void*)consumer, (void*)&ids[i]);
73 for (int i = 0; i < ProducerCount; i++)
74 pthread_join(pro[i], NULL);
75 for (int i = 0; i < ConsumerCount; i++)
76 pthread_join(con[i], NULL);
78 pthread_mutex_destroy(&mutex);