0% found this document useful (0 votes)
17 views16 pages

Ex 2 - 5 Os Lab Program

Uploaded by

hemumullavanam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views16 pages

Ex 2 - 5 Os Lab Program

Uploaded by

hemumullavanam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

lO M oA R cP S D| 28114020 l

O
Mo
AR
cP
SD
|
2
8
1
1
4
0
2
0

EX:NO:2 Process Creation using fork() and Usage of getpid(),


getppid(), wait() functions

Aim :
To write a program for process Creation using fork() and usage of getpid(), getppid(),
wait() function.

Program :
• Process creating using fork()

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int
main(){
fork();
fork();
printf("Hello World\n");
}

Output

• Usage of getpid() and getppid()


#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void main()
{
lO M oA R cP S D| 2 81 1 40 20

//variable to store calling function's


int process_id, p_ process_id;
//getpid() - will return process id of calling function
process_id = getpid();
//getppid() - will return process id of parent function
p_process_id = getppid();
//printing the process ids
printf("The process id: %d\n",process_id);
printf("The process id of parent function: %d\n",p_process_id);
}
Output :

• Usage of wait()
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
pid_t cpid;
if (fork()== 0)
exit(0); /* terminate child */
else
cpid = wait(NULL); /* reaping parent */
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);
return 0;
}
lO M oA R cP S D| 2 81 1 40 20

Output:

Result :

Thus Successfully completed Process Creation using fork() and Usage of getpid(),
getppid(), wait() functions.
lO M oA R cP S D| 2 81 1 40 20

EX:NO 3 Multithreading and pthread in C

Aim :

To implement and study Multithreading and pthread in C


Program :
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX 1000
#define MAX_THREAD 4
int array[1000];
int sum[4] = { 0 };
int arraypart = 0;

void* sum_array(void* arg)


{
int thread_part = arraypart++;

for (int i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)
{
sum[thread_part] += array[i];
}
}

void testSum()
{
pthread_t threads[MAX_THREAD];

for (int i = 0; i < MAX_THREAD; i++)


{
pthread_create(&threads[i], NULL, sum_array, (void*)NULL);
}

// joining threads
for (int i = 0; i < MAX_THREAD; i++)
{
pthread_join(threads[i], NULL);
}

// print each thread


for (int i = 0; i < MAX_THREAD; i++)
{
printf("Thread %d Sum is : %d \n",i, sum[i]);
}
lO M oA R cP S D| 2 81 1 40 20

// adding the 4 parts


int total_sum = 0;
for (int i = 0; i < MAX_THREAD; i++)
{
total_sum += sum[i];
}
printf("\nTotal Sum is : %d \n",total_sum);

}
void readfile(char* file_name)
{
char ch;

FILE *fp;

fp = fopen(file_name,"r"); // read mode

if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}

char line [5]; /* line size */

int i=0;

printf("Reading file: ");


fputs(file_name,stdout);
printf("\n");

while ( fgets ( line, sizeof line, fp) != NULL ) /* read a line */


{
if (i < 1000)
{
array[i]=atoi(line);
}

i++;
}
lO M oA R cP S D| 2 81 1 40 20

fclose(fp);

printf("Reading file Complete, integers stored in array.\n\n");

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


{

if (argc != 2) {
fprintf(stderr,"usage: a.out <file name>\n");
/*exit(1);*/
return -1;
}

readfile(argv[1] );

//Debug code for testing only


testSum();

return 0;
}
Output :

Result :

Successfully implemented and studied Multithreading and pthread in C


lO M oA R cP S D| 2 81 1 40 20

EX:NO 4 Mutual Exclusion using semaphore and monitor

Aim :
To implement Mutual Exclusion using semaphore and monitor

Program :
USING SEMAPHORE
#include<stdio.h>

#include<pthread.h>
#include<semaphore.h>

#include<unistd.h>
#include<errno.h>
#include <stdlib.h>

#include<sched.h>
int philNo[5] = { 0, 1, 2, 3, 4 };
// my_semaphore structure
typedef struct {

// Semaphore mutual exclusion variable


pthread_mutex_t mutex;

// Semaphore count variable


int cnt;

// Semaphore conditonal variable


pthread_cond_t conditional_variable;

}
my_semaphore;

// Function to initialise the semaphore variables


int init(my_semaphore *sema, int pshared, int val) {

// The case when pshared == 1 is not implemeted as it was not required because the
philosphers are implemented using threads and not processes.
lO M oA R cP S D| 2 81 1 40 20

if(pshared == 1){
printf("Cannot handle semaphores shared between processes!!! Exiting\n");
return -1;
}

// Initialisng the semaphore conditonal variable


pthread_cond_init(&sema->conditional_variable, NULL);

// Initialisng the semaphore count variable


sema->cnt = val;

// Initialisng the semaphore mutual exclusion variable


pthread_mutex_init(&sema->mutex, NULL);

return 0;
}

int signal(my_semaphore *sema) {

//This locks the mutex so that only thread can access the critical section at a time
pthread_mutex_lock(&sema->mutex);

sema->cnt = sema->cnt + 1;

// This wakes up one waiting thread


if (sema->cnt)

pthread_cond_signal(&sema->conditional_variable);
lO M oA R cP S D| 2 81 1 40 20

// A woken thread must acquire the lock, so it will also have to wait until we call unlock

// This releases the mutex


pthread_mutex_unlock(&sema->mutex);

return 0;
}

int wait(my_semaphore *sema) {


//This locks the mutex so that only thread can access the critical section at a time
pthread_mutex_lock(&sema->mutex);

// While the semaphore count variable value is 0 the mutex is blocked on the conditon
variable
while (!(sema->cnt))
pthread_cond_wait(&sema->conditional_variable, &sema->mutex);
// unlock mutex, wait, relock mutex

sema->cnt = sema->cnt - 1;

// This releases the mutex and threads can access mutex


pthread_mutex_unlock(&sema->mutex);

return 0;

}
// Print semaphore value for debugging
void signal1(my_semaphore *sema) {
printf("Semaphore variable value = %d\n", sema->cnt);

}
// Declaring the semaphore variables which are the shared resources by the threads
my_semaphore forks[5], bowls;

//Function for the philospher threads to eat


void *eat_food(void *arg) {

while(1) {
int* i = arg;
// This puts a wait condition on the bowls to be used by the current philospher so
that the philospher can access these forks whenever they are free
wait(&bowls);
lO M oA R cP S D| 2 81 1 40 20

// This puts a wait condition on the forks to be used by the current philospher so
that the philospher can access these forks whenever they are free
wait(&forks[*i]);
wait(&forks[(*i+4)%5] );
sleep(1);
//Print the philospher number, its thread ID and the number of the forks it uses for
eating printf("Philosopher %d with ID %ld eats using forks %d and %d\n", *i+1,
pthread_self(), *i+1, (*i+4)%5+1);
// This signals the other philospher threads that the bowls are available for
eating signal(&bowls);

// This signals the other philospher threads that these forks are available for
eating and thus other threads are woken up
signal(&forks[*i]);
signal(&forks[(*i+4)%5]);
sched_yield();
}

}
void main() {
int i = 0;
// Initialising the forks (shared variable) semaphores
while(i < 5){
init(&forks[i], 0, 1);
i++;
}

// Initialising the bowl (shared variable) semaphore


init(&bowls, 0, 1);

// Declaring the philospher threads


pthread_t phil[5];

i = 0;
// Creating the philospher threads
while(i < 5) {

pthread_create(&phil[i], NULL, eat_food, &philNo[i]);


lO M oA R cP S D| 2 81 1 40 20

i++;
}
i = 0;
// Waits for all the threads to end their execution before ending
while(i < 5) {
pthread_join(phil[i], NULL);
i++;
}}
Output :

USING MONITOR
monitor DP

{
status state[5];
condition self[5];
// Pickup chopsticks
Pickup(int i)

{
// indicate that I’m hungry
state[i] = hungry;

// set state to eating in test()


// only if my left and right neighbors
// are not eating
test(i);
lO M oA R cP S D| 2 81 1 40 20

// if unable to eat, wait to be signaled if


(state[i] != eating)
self[i].wait;

// Put down chopsticks


Putdown(int i)
{
// indicate that I’m thinking
state[i] = thinking;

// if right neighbor R=(i+1)%5 is hungry and


// both of R’s neighbors are not eating,
// set R’s state to eating and wake it up by

// signaling R’s CV

test((i + 1) % 5);
test((i + 4) % 5);

}
test(int i)
{
if (state[(i + 1) % 5] != eating
&& state[(i + 4) % 5] != eating
&& state[i] == hungry) {
// indicate that I’m eating
state[i] = eating;

// signal() has no effect during Pickup(),


// but is important to wake up waiting
// hungry philosophers during Putdown()
self[i].signal();
}
}
init()
{
// Execution of Pickup(), Putdown() and test()
// are all mutually exclusive,
// i.e. only one at a time can be executing
for
i = 0 to 4
// Verify that this monitor-based solution is
// deadlock free and mutually exclusive in that
// no 2 neighbors can eat simultaneously
state[i] = thinking;
}
}

Output :

Result :

Successfully executed Mutual Exclusion using semaphore and monitor


EX:NO:5 Reader-Writer problem

Aim :

To study the Reader – Writer problem

Program :
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t wrt;

pthread_mutex_t

mutex; int cnt = 1;

int numreader = 0;
void *writer(void *wno)
{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);

sem_post(&wrt);
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);

numreader++;
if(numreader == 1) {

sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);

numreader--;
if(numreader == 0) {

sem_post(&wrt); // If this is the last reader, it will wake up the writer.


}
pthread_mutex_unlock(&mutex);

}
int main()

{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);

int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the producer and consumer
for(int i = 0; i < 10; i++) {

pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i] );


}
for(int i = 0; i < 5; i++) {

pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i] );


}
for(int i = 0; i < 10; i++) {
pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++) {

pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);

return 0;

}
Output:

Result:
Thus Successfully provided a solution to Reader – Writer using mutex and semaphore.

You might also like