Friday 5 February 2016

Robots Moving Up & Down Linux Semaphore Example (C) | Semaphore in Operating System

Robots Moving Up & Down Linux Semaphore Example (C) | Semaphore in Operating System

Description:    Consider a situation in which some robots are moving up and down a ladder. The ladder is narrow and hence only one robot can climb up or down at a time. However, multiple robots can move in one direction at the same time.

The following code runs this situation for such moving robots. The climbing is synchronize using semaphores in operating system.

Code in C

#include<stdio.h>
#include<unistd.h>
#include<stdbool.h>
#include<pthread.h>
#include<semaphore.h>

sem_t move;
sem_t turn;

pthread_mutex_t up_mutex;
pthread_mutex_t down_mutex;

int up_count=0;
int down_count=0;
int time_elapsed=0;

void *UP(void *param){
   int no,s_t;
   no=(int*)param;
  
   time_elapsed=rand()%3+2+time_elapsed;
   sleep(time_elapsed);
  
   sem_wait(&turn);
  
   pthread_mutex_lock(&up_mutex);
  
   if((++up_count)==1)
      sem_wait(&move);
   sem_post(&turn);
   pthread_mutex_unlock(&up_mutex);
   printf("UP_Robot#%d starts moving UP\n",no);
   sleep(4);        //Robot Moving
   printf("UP_Robot#%d has climed UP\n",no);
   pthread_mutex_lock(&up_mutex);
  
   if((--up_count)==0)
      sem_post(&move);

   pthread_mutex_unlock(&up_mutex);  

}

void *DOWN(void *param){
   int no,s_t;
   no=(int*)param;
  
   time_elapsed=rand()%5+2+time_elapsed;
   sleep(time_elapsed);
  
   sem_wait(&turn);

   pthread_mutex_lock(&down_mutex);
  
   if((++down_count)==1)
      sem_wait(&move);
   sem_post(&turn);

   pthread_mutex_unlock(&down_mutex);
   printf("DOWN_Robot#%d starts going DOWN\n",no);
   sleep(4);       //Robot Moving
   printf("DOWN_Robot#%d has reached the bottom\n",no);
   pthread_mutex_lock(&down_mutex);
  
   if((--down_count)==0)
      sem_post(&move);
         
   pthread_mutex_unlock(&down_mutex);
}

int main(int argc,char *argv[]){

   sem_init(&move, 2, 1);
   sem_init(&turn, 2, 1);
  
  
   pthread_mutex_init(&up_mutex,NULL);
   pthread_mutex_init(&down_mutex,NULL);

   int i,sleep_time,no_of_up_threads,no_of_down_threads;
  
   sleep_time=atoi(argv[1]);
   no_of_up_threads=atoi(argv[2]);
   no_of_down_threads=atoi(argv[3]);
  
   pthread_t threadID;
   pthread_attr_t attributes;
   pthread_attr_init (&attributes);

   for(i=0;i<no_of_up_threads;i++)
      pthread_create(&threadID,&attributes,UP,i+1);
     
   for(i=0;i<no_of_down_threads;i++)
      pthread_create(&threadID,&attributes,DOWN,i+1);
     
   sleep(sleep_time);

   return 0;
}


No comments

Post a Comment

Recent Posts