Synchronization primitives: Mutex and Semaphore (Sample Program) - Article 9
Hi Folks, In this article, I am going to present my version of producer consumer problem which we need to synchronize. The producer can produce a maximum of 5 elements and the consumer consumes 1 element at a time. All data is shared and hence, synchronization is needed. In this article, I am going to present the program. In the next article, we shall apply synchronization. #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<pthread.h> #include<stdio.h> #include<stdlib.h> typedef struct node { struct node *link; int data; } NODE; static int count = 0; NODE *head = NULL; NODE *get_node(void) { int data = rand(); data = data % 13; NODE *ptr = (NODE *)malloc(sizeof(NODE)); if(ptr != NULL) { ptr->data = data; ptr->link = NULL; } return ptr; } void print_node(NODE *ptr) { printf("|%d|",ptr->data); if(ptr->link != NULL) {