Skip to content

Instantly share code, notes, and snippets.

@manku-timma
Created July 22, 2014 00:37
Show Gist options
  • Save manku-timma/6580600e0e52d7531bf1 to your computer and use it in GitHub Desktop.
Save manku-timma/6580600e0e52d7531bf1 to your computer and use it in GitHub Desktop.
Example program for producer-consumer implementation using pthread apis
#include <stdio.h>
#include <pthread.h>
#define MAX 1024
int shared_buffer[MAX];
int producer_index;
int consumer_index;
int num_items;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int global_id = 1;
void* producer(void* data) {
while (1) {
pthread_mutex_lock(&mutex);
while (num_items == MAX) {
printf("%p(P): Waiting on full\n", pthread_self());
pthread_cond_wait(&cond, &mutex);
}
shared_buffer[producer_index] = global_id;
global_id++;
producer_index = (producer_index + 1) % MAX;
num_items++;
printf("%p(P:%d:%d): Produced %d\n", pthread_self(), num_items, producer_index, global_id - 1);
if (num_items == 1) { pthread_cond_signal(&cond); }
pthread_mutex_unlock(&mutex);
}
}
void* consumer(void* data) {
while (1) {
pthread_mutex_lock(&mutex);
while (num_items == 0) {
printf("%p(C): Waiting on empty\n", pthread_self());
pthread_cond_wait(&cond, &mutex);
}
int x = shared_buffer[consumer_index];
printf("%p(C:%d:%d): Consumed %d\n", pthread_self(), num_items, consumer_index, x);
consumer_index = (consumer_index + 1) % MAX;
num_items--;
if (num_items == MAX - 1) { pthread_cond_signal(&cond); }
pthread_mutex_unlock(&mutex);
}
}
#define PRODUCERS 20
#define CONSUMERS 10
int main() {
pthread_t producer_threads[PRODUCERS];
pthread_t consumer_threads[CONSUMERS];
for (int i = 0; i < PRODUCERS; ++i) {
pthread_create(&producer_threads[i], NULL, producer, NULL);
}
for (int i = 0; i < CONSUMERS; ++i) {
pthread_create(&consumer_threads[i], NULL, consumer, NULL);
}
void* ret;
for (int i = 0; i < PRODUCERS; ++i) {
pthread_join(producer_threads[i], &ret);
}
for (int i = 0; i < CONSUMERS; ++i) {
pthread_join(consumer_threads[i], &ret);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment