Mutex

 

Expt No: 5                        Mutual Exclusion

Date:                        (Producer Consumer Problem)

 

 

Aim: To demonstrate mutual exclusion using mutex in Producer Consumer application.

 

Program :

// Producer Consumer Problem

#include <pthread.h>          

#include <stdio.h>

#include <stdlib.h>

#include </usr/include/semaphore.h>

#include <unistd.h>     // for sleep

 

#define BUFSIZE        5      /* total number of slots */

#define NP                 1               /* total number of producers */

#define NC                 1               /* total number of consumers */

#define NITEMS         5      /* number of items produced/consumed */

 

typedef struct

{

    int buf[BUFSIZE];  /* shared var */

    int in;                    /* buf[in%BUFSIZE] – first empty slot */

    int out;                   /* buf[out%BUFSIZE] – first full slot */

    sem_t full;              /* keep track of number of full spots */

    sem_t empty;          /* keep track of number of empty spots */

 

    /* enforce mutual exclusion to shared data */

    pthread_mutex_t mutex;

} sbuf_t;

sbuf_t shared;

 


 

void *Producer(void *arg)

{

    int i, item;

 

    for (i=1; i <=NITEMS; i++)

    {

        item = i;    /* Produce item */

 

        /* Prepare to write item to buf */

        /* If there are no empty slots, wait */

        sem_wait(&shared.empty);

 

        /* If another thread uses the buffer, wait */

        pthread_mutex_lock(&shared.mutex);

        shared.buf[shared.in] = item;

        shared.in = (shared.in+1)%BUFSIZE;

        printf("Produced : %d\n", item);

        fflush(stdout);

 

 

        /* Release the buffer */

        pthread_mutex_unlock(&shared.mutex);

 

        /* Increment the number of full slots */

        sem_post(&shared.full);

       

        /* Interleave  producer and consumer execution */

        sleep(1);

    }

    return NULL;

}

 


 

void *Consumer(void *arg)

{

int i, item;

 

for (i=NITEMS; i > 0; i--)

{

sem_wait(&shared.full);

 

pthread_mutex_lock(&shared.mutex);

item=i;

item=shared.buf[shared.out];

shared.out = (shared.out+1)%BUFSIZE;

 

printf("\tConsumed : %d\n", item);

        fflush(stdout);

 

/* Release the buffer */

pthread_mutex_unlock(&shared.mutex);

 

/* Increment the number of full slots */

sem_post(&shared.empty);

 

/* Interleave  producer and consumer execution */

sleep(1);

}

return NULL;

}

 


 

int main()

{

pthread_t idP, idC;

 

sem_init(&shared.full, 0, 0);

sem_init(&shared.empty, 0, BUFSIZE);

pthread_mutex_init(&shared.mutex, NULL);

 

/* Create a new producer */

pthread_create(&idP, NULL, Producer, (void*)NP);

 

/*create a new Consumer*/

pthread_create(&idC, NULL, Consumer, (void*)NC);

 

pthread_exit(NULL);

}

 

 

Result: Thus the program to demonstrate mutual exclusion using mutex was written and executed.

 

 

InterProcess Communication

 

Expt No: 4                       Inter–Process Communication

Date:

 

Aim: To develop application to illustrate Inter Process Communication among processes using Shared memory, Pipes and Message Queue.

 

Program :

// 1. IPC Using Shared Memory – Server Program

#include <sys/shm.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

#define MAXSIZE 128

 

void die(char *s) {

    perror(s);

    exit(1);

}

 

int main() {

    int shmid;

    key_t key;

    char *shm;

   

    key = 5678;

 

    if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)

        die("shmget");

 

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)

        die("shmat");

   

    printf("Enter a message: ");

    fgets(shm, MAXSIZE, stdin);

    shm[strcspn(shm, "\n")] = 0; // Remove newline character

   

    printf("Message written to shared memory.\n");

    exit(0);

}

 

// 1. IPC Using Shared Memory – Client Program

 

#include <sys/shm.h>

#include <stdio.h>

#include <stdlib.h>

 

#define MAXSIZE     27

 

void die(char *s)

{

     perror(s);

     exit(1);

}

 

int main()

{

     int shmid;

     key_t key;

     char *shm, *s;

     key = 5678;

 

     if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)

         die("shmget");

 

     if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)

         die("shmat");

    printf("\nMessage read from shared memory - ");

     for (s = shm; *s != '\0'; s++)

         putchar(*s);

     putchar('\n');

 

     exit(0);

}

 

 


 

// 2. IPC Using Message Queue

// Sender Program

 

#include <sys/msg.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

#define MAXSIZE 128

 

struct msgbuf {

    long mtype;

    char mtext[MAXSIZE];

};

 

int main() {

    int msqid;

    key_t key = 1234;

    struct msgbuf sbuf;

    size_t buflen;

 

    if ((msqid = msgget(key, IPC_CREAT | 0666)) < 0) {

        perror("msgget");

        exit(1);

    }

 

    sbuf.mtype = 1;

    printf("Enter a message: ");

    fgets(sbuf.mtext, MAXSIZE, stdin);

    buflen = strlen(sbuf.mtext) + 1;

 

    if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0) {

        perror("msgsnd");

        exit(1);

    }

    printf("Message Sent\n");

    return 0;

}

 


 

// 2. IPC Using Message Queue

// Receiver Program

 

#include <sys/msg.h>

#include <stdio.h>

#include <stdlib.h>

 

#define MSGSZ 128

 

struct msgbuf {

    long mtype;

    char mtext[MSGSZ];

};

 

int main() {

    int msqid;

    key_t key = 1234;

    struct msgbuf rbuf;

 

    if ((msqid = msgget(key, 0666)) < 0) {

        perror("msgget");

        exit(1);

    }

    if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {

        perror("msgrcv");

        exit(1);

    }

 

    printf("Received Message: %s\n", rbuf.mtext);

    return 0;

}

 


 

// 3. IPC Using Pipes

 

#include<stdio.h>

#include<unistd.h>

#include<string.h>

#include<sys/types.h>

#include<sys/wait.h>

 

int main()

{

    int p1[2], p2[2];

    char str[25];

 

    printf("\nIPC USING PIPES\n");

    printf("Enter Message to send : ");

        scanf("%s",str);

 

    pipe(p1);

    pipe(p2);

    write(p1[1],str,sizeof(str));

 

    int a=fork();

    if(a==0)

    {

        printf("\n Child Process :");

        printf("\n Child process pid=%d ", getpid());

        printf("\n Parent process pid=%d ", getppid());

        read(p1[0],str,sizeof(str));

        printf("\n\tMessage received from Parent process : %s\n",str);

        write(p2[1],str,sizeof(str));

    }

    else

    {

        wait(NULL);

        printf("\n Parent Process :");

        printf("\n Parent process pid=%d ", getpid());

        read(p2[0],str,sizeof(str));

        printf("\n\tMessage returned from Child process : %s\n\n",str);

    }

 }

 

 

 

Result: Thus the programs to demonstrate Inter Process Communication among processes using Shared memory, Message Queue and Pipes were written and executed.