Posts

Showing posts from April, 2018

Reader -Writer Program

What is reader writer problem? Read this link to know this problem: https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem Following algorithm is implement using pthread lib. Reader() { lock(read) if(reader==0)    lock(write) reader++ unlock(read) reader from shared resource lock(read) reader-- if(reader == 0)    unlock(write) unlock(read) } // Writer thread writer() { produce item lock(write) write item to shared resource unlock(write) } [sourcecode language="CPP" highlight=""] #include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> #define MAX 20 // Shared buffer with default value char buffer[MAX] = "Sacheen Birhade"; // Variable to count number of readers volatile int reader = 0; // read and write mutex pthread_mutex_t write = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t read = PTHREAD_MUTEX_INITIALIZER; // Helper function to generate random stri...

Print numbers in sequence using thread synchronization

The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ….. print n in nth thread and again repeat from thread 1 infinitely. Example: Input : Thread count Output : 1 2 3 ... thread count 1 2 3 ... thread  count 1 2 3 ... thread count .... Input : 5 Output : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5  1 2 3 4 5 1 2 3 4 5 .... // C code to synchronize threads #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t* cond = NULL; int threads; volatile int cnt = 0; // function to synchronize threads void* foo(void* arg) {     // turn is a basically to identify a thread     int turn = *(int*)arg;         while (1) {         pthrea...

Producer-Consumer Problem Using Semphore

#include<stdio.h> #include<pthread.h> #include<stdlib.h> #include <semaphore.h> #define Buffer_Limit 10 int Buffer_Index_Value = -1; char *Buffer_Queue; sem_t mutex,empty_count,fill_count;  void *Consumer() {       while(1)       {    sem_wait(&fill_count);    sem_wait(&mutex);    printf("Consumer:%d\t", Buffer_Index_Value--);           sem_post(&mutex);    sem_post(&empty_count);          }    } void *Producer() {          while(1)       {     sem_wait(&empty_count);             sem_wait(&mutex);             Buffer_Queue[++Buffer_Index_Value] = '@';             printf("Producer:%d\t", Buffer_Index_Value);     sem_...