/** * A simple consumer-producer problem without synchronization. * This program will generate incorrect results. * This is to demonstrate the potential issues with multiple threads/processes. */ #include #include #include #include #define false 0 #define true 1 #include "buffer.h" #define BFSIZE 5 void * producer(); void * consumer(); int count; // number of items in the buffer int in; // index to the next free position int out; // index to the next full position int order = 0;// total number of products so far struct product_t * buffer[BFSIZE]; int main(int argc, char *argv[]) { pthread_t tid[2]; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ // buffer is initially empty count = 0; in = 0; out = 0; /* create the producer thread */ pthread_create(&tid[0], NULL, producer, NULL); /* create the consumer thread */ pthread_create(&tid[1], NULL, consumer, NULL); /* now wait for the thread to exit */ pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); return 0; } void * producer() { struct product_t * item; int i = 0; while (i < 100) { // repeat item = make_item(); insert_item(item); i ++; } } void insert_item(struct product_t * item) { while (count >= BFSIZE); // do nothing -- no free buffers printf("producer: count in p %d\n", count); fflush(stdout); // now we have a free slot, add an item to the buffer ++count; buffer[in] = item; in = (in + 1) % BFSIZE; } void * consumer() { struct product_t * item; int i = 0; while (i < 100) { // repeat item = remove_item(); consume_item(item); i ++; } } struct product_t * remove_item() { struct product_t * item; while (count == 0); // do nothing -- nothing to consume printf(" -- consumer: count in c %d\n", count); fflush(stdout); // remove an item from the buffer --count; item = buffer[out]; out = (out + 1) % BFSIZE; return item; } void consume_item(struct product_t *item) { printf(" -- consumer: product name %s\n", item->name); printf(" -- consumer: product value %10.2f\n", item->value); fflush(stdout); } struct product_t * make_item() { struct product_t * an_item = (struct product_t *)malloc(sizeof(struct product_t)); char number[32]; strcpy(an_item->name, "Name "); sprintf(number, "%d", order); strcat(an_item->name, number); order ++; an_item->value = 100; return an_item; }