implementing of classical synchronization problem by using semaphores

12
1) Implementing of classical synchronization problem by using semaphores Here my problem is an agent has a cars and bikes, if one has taken the car the other has to wait to drive the car and if a bike is taken by a one person and same as other customer has to wait for the completion of drive. The code is as follows the problem. #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> union semun { int mutex; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ } un; void main() { int id,KEY=55,val,mutex1,mutex2; struct sembuf seu[1]; id = semget(KEY, 1, IPC_CREAT|0777); if(id < 0) { printf("Semaphore not created"); } seu[0].sem_num=1; seu[0].sem_op = -1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\n Customer taking car\n"); } else { printf("sem1: operation did not succeed.\n"); perror("Reason");

Upload: gowtham-reddy

Post on 14-Apr-2017

12 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Implementing of classical synchronization problem by using semaphores

1) Implementing of classical synchronization problem by using semaphores Here my problem is an agent has a cars and bikes, if one has taken the car the other has to wait to drive the car and if a bike is taken by a one person and same as other customer has to wait for the completion of drive. The code is as follows the problem.

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h>

union semun { int mutex; /* Value for SETVAL */

struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ } un; void main(){ int id,KEY=55,val,mutex1,mutex2; struct sembuf seu[1];

id = semget(KEY, 1, IPC_CREAT|0777); if(id < 0)

{ printf("Semaphore not created");}

seu[0].sem_num=1; seu[0].sem_op = -1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\n Customer taking car\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }

{ int wait; wait=rand() % 50; printf("\n Customer took car\n"); sleep(wait);}

Page 2: Implementing of classical synchronization problem by using semaphores

seu[0].sem_num=1; seu[0].sem_op = 1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\nAnother customer can take car\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }}

And the customer has taken the bike and then the code as follows:

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h>

union semun { int mutex; /* Value for SETVAL */

struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ } un; void main(){ int id,KEY=55,val,mutex1,mutex2; struct sembuf seu[1];

id = semget(KEY, 1, IPC_CREAT|0777); if(id < 0)

{ printf("Semaphore not created");}

seu[0].sem_num=0; seu[0].sem_op = -1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) {

Page 3: Implementing of classical synchronization problem by using semaphores

printf("\n Customer taking bike\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }

{ int wait; wait=rand() % 50; printf("\n Customer took bike\n"); sleep(wait);}

seu[0].sem_num=0; seu[0].sem_op = 1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\nAnother customer can take bike\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }}

3) semaphore intitilisation.

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h> union semun { int mutex; /* Value for SETVAL */

int mutex1; struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ } un;

void main(){

Page 4: Implementing of classical synchronization problem by using semaphores

int id,KEY=55,mutex,mutex1; struct sembuf seu[1];

id = semget(KEY,2, IPC_CREAT|0777); if(id < 0)

{ printf("Semaphore not created");}

un.mutex = 2; mutex=semctl(id,0,SETVAL,un); if(mutex == 0) { printf("Successful Init\n"); printf("Sem ID is %d\n", id); } else { printf("UnSuccessful Init\n"); } un.mutex1 = 1; mutex=semctl(id,1,SETVAL,un); if(mutex == 0) { printf("Successful Init\n"); printf("Sem ID is %d\n", id); } else { printf("UnSuccessful Init\n"); }

}

4) In the below program complete synchronisation done with semaphores and problem solved#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>#include <sys/types.h>

union semun { int mutex; /* Value for SETVAL */

struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */

Page 5: Implementing of classical synchronization problem by using semaphores

struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ } un; void main(){ int id,KEY=55,val,mutex1,mutex2; struct sembuf seu[1];

id = semget(KEY, 1, IPC_CREAT|0777); if(id < 0)

{ printf("Semaphore not created");}

mutex1=semctl(id,0,GETVAL,un); mutex2=semctl(id,1,GETVAL,un);

if(mutex1 == 0) { printf("\nbike busy\n"); }else { seu[0].sem_num=0;

seu[0].sem_op = -1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\n Customer can take bike\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }

{ int wait; wait=rand() % 50; printf("\n Customer took bike\n"); sleep(wait);}

seu[0].sem_num=0; seu[0].sem_op = 1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\nAnother customer can take bike\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }

}

Page 6: Implementing of classical synchronization problem by using semaphores

if(mutex2 == 0) { printf("\ncar busy\n"); }

else{ seu[0].sem_num=1; seu[0].sem_op = -1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\n Customer taking car\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }

{ int wait; wait=rand() % 50; printf("\n Customer took car\n"); sleep(wait);}

seu[0].sem_num=1; seu[0].sem_op = 1; seu[0].sem_flg = 0; val=semop(id,seu,1); if(val == 0) { printf("\nAnother customer can take car\n"); } else { printf("sem1: operation did not succeed.\n");

perror("Reason"); }}

}

2) Implementing of classical synchronization problem by using threads

cars-Customer solution using threads in Java In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.

Page 7: Implementing of classical synchronization problem by using semaphores

The producer/cars’s job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming/using the data (i.e. removing it from the buffer), one piece at a time.Problem to make sure that the producer/cars won’t try to add data into the buffer if it’s full and that the custamer won’t try to remove data from an empty buffer.Solution The producer/cars is to either go to sleep or discard data if the buffer is full. The next time the consumer/customer removes an item from the buffer, it notifies the producer/cars, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer/cars puts data into the buffer, it wakes up the sleeping consumer/customer. An inadequate solution could result in a deadlock where both processes are waiting to be awakened.Recommended Reading- Multithreading in JAVA, Synchronized in JAVA, Inter-thread CommunicationImplementation of Producer Consumer ClassA Linked List list – to store list of jobs in queue. A Variable Capacity – to check for if the list is full or not A mechanism to control the insertion and extraction from this list so that we do not insert into list if it is full or remove from it if it is empty.Note: It is recommended to test the below program on a offline IDE as infinite loops and sleep method may lead to it time out on any online IDE// Java program to implement solution of producer // consumer problem. Import java.util.LinkedList;   public class Threadexample {     public static void main(String[] args)        //throws Interrupted Exception//throws Interrupted Exception {         // Object of a class that has both cars ()     // and customer () methods         Final PC pc = new PC();           // Create cars thread         Thread t1 = new Thread(new Runnable()         {             @Override             public void run()             {                 try                 {                     pc.cars();              

Page 8: Implementing of classical synchronization problem by using semaphores

   }                 catch(InterruptedException e)                 { e.printStackTrace();                 }             }         });           // Create customer thread         Thread t2 = new Thread(new Runnable()         {             @Override             public void run()             {                 try                 {                     pc.customer();                 }                 catch(InterruptedException e)                 {                     e.printStackTrace();                 }             }         });           // Start both threads         t1.start();         t2.start();           // t1 finishes before t2         t1.join();         t2.join();     }       // This class has a list, cars (adds items to list     // and customer (removes items).     public static class PC     {         // Create a list shared by producer and customer         // Size of list is 2. LinkedList<Integer> list = new LinkedList<>();         int capacity = 2;           // Function called by producer thread         public void cars() throws InterruptedException         {             int value = 0;             while (true)             {                 synchronized (this)

Page 9: Implementing of classical synchronization problem by using semaphores

                {                     // producer thread waits while list                     // is full                     while (list.size()==capacity)                        wait();   System.out.println("cars produced-"+value);                       // to insert the jobs in the list list.add(value++);              // notifies the customer thread that             // now it can start using                     notify();                       // makes the working of program easier                     // to  understand                     Thread.sleep(1000);                 }             }         }           // Function called by customer thread         public void use() throws InterruptedException         {             while (true)             {                 synchronized (this)                 {                     // customer thread waits while list                     // is empty                     while (list.size()==0)                         wait();                       //to retrive the ifrst job in the list     

                int val = list.removeFirst();                       System.out.println("Customer used-"+val);                       // Wake up cars thread                     notify();                       // and sleep                     Thread. Sleep (1000);                 }    }         }     } }

Page 10: Implementing of classical synchronization problem by using semaphores

Output:Cars produced-0 Cars produced-1 Customer used-0Customer used-1Cars produced-2