Thursday, November 21, 2013

Unix Network Programming: Process synchronization using semaphore

Algorithm


main() function
  1. Create a semaphore
  2. fork()
  3. In both parent and child
    1. Obtain lock by calling lock() function
    2. sleep for some time
    3. unlock by calling unlock() function
lock() function
  1. Create array of sembuf with size two
    1. First element waiting for semaphore to be zero
    2. Second element incrementing it
  2. Do semop with the created array as argument
unlock() function
  1. Create array of sembuf with size one
    1. The element decrementing semaphore
  2. Do semop with the created array as argument

Program

#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#define PERMS 0666
#define KEY 1234

main(){
    int pid,semid,i;
    semid = semget(KEY, 1, IPC_CREAT|PERMS);
    pid = fork();
    if(pid == 0){                // Child Process
        for(i=1;i<=5;i++){
            printf("%d: Child waiting for lock\n",i);
            lock(semid);
                printf("%d: Child has the lock\n",i);
                sleep(1);
                printf("%d: Child unlocking\n",i);
            unlock(semid);
        }
    }else{                        // Parent Process
        for(i=1;i<=5;i++){
            printf("%d: Parent waiting for lock\n",i);
            lock(semid);
                printf("%d: Parent has the lock\n",i);
                sleep(1);
                printf("%d: Parent unlocking\n",i);
            unlock(semid);       
        }
    }
}

lock(int id){
    struct sembuf op_lock[2]={
        0, 0, 0,                   // Wait for id to be 0
        0, 1, 0                    // Then increment it
    };
    semop(id, op_lock,2);
}

unlock(int id){
    struct sembuf op_unlock[1]={
        0, -1, IPC_NOWAIT        // Decrement semid by 1
    };
    semop(id,op_unlock,1);
}

Output

1: Parent waiting for lock
1: Parent has the lock
1: Child waiting for lock
1: Parent unlocking
2: Parent waiting for lock
1: Child has the lock
1: Child unlocking
2: Child waiting for lock
2: Parent has the lock
2: Parent unlocking
3: Parent waiting for lock
2: Child has the lock
2: Child unlocking
3: Child waiting for lock
3: Parent has the lock
3: Parent unlocking
4: Parent waiting for lock
3: Child has the lock
3: Child unlocking
4: Child waiting for lock
4: Parent has the lock
4: Parent unlocking
5: Parent waiting for lock
4: Child has the lock
4: Child unlocking
5: Child waiting for lock
5: Parent has the lock
5: Parent unlocking
5: Child has the lock
5: Child unlocking

No comments:

Post a Comment