Assignment: Lovely Professional University
Assignment: Lovely Professional University
CSE325
Name: Abdullah Al Hasan
Reg.No:11800290
Roll: 10
Section: K18AZ
Email:[email protected]
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
void*function1();
void*function2();
int main()
{
pthread_t thread1,thread2;
pthread_create(&thread2,NULL,function2,NULL);
pthread_create(&thread1,NULL,function1,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
}
void*function1()
{
printf("thread t1");
}
void*function2()
{
sleep(1);
printf("\n thread t2");
}
Write a program to avoid race condition using semaphores.
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
void*function1();
void*function2();
int shared=1;sem_t s;
int main()
{
sem_init(&s,0,1);
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,function1,NULL);
pthread_create(&thread2,NULL,function2,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("the output is %d\n",shared);
}
void*function1()
{
int a;
sem_wait(&s);
a=shared;
a++;
sleep(2);
shared=a;
sem_post(&s);
}
void*function2()
{
int b;
sem_wait(&s);
b=shared;
b--;
sleep(2);
shared=b;
sem_post(&s);
}
Write a program in which child process will send a message “Hello, this is child process”
to the parent using a communication channel pipe.
The parent will continue its execution and print “This is parent” after receiving message
from child.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int retval;
int file_descriptor[5];
int n;
retval=pipe(file_descriptor);
if(retval<0)
{
printf("the Pipe is fail\n");
exit(0);
}
pid=fork();
if(pid==0)
{
close(file_descriptor[0]);
n=write(file_descriptor[1],"\n Hello this is child process",30);
exit(0);
}
else if (pid>0)
{
char buffer[100];
close(file_descriptor[1]);
n=read(file_descriptor[0],buffer,100);
buffer[n]='\0';
printf("this is parent %s\n",buffer);
}
return 0;
}
Write a program to create a deadlock using two processes and two resources.
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
pthread_mutex_t resource1,resourec2;
int test=0;
void*process1()
{
return 0;
}
void*process2()
{
printf("\n process2 using resource2");
pthread_mutex_lock(&resource2);
usleep(200);
printf("\nprocess2 trying to get resource1");
pthread_mutex_lock(&resource1);
test--;
printf("\n process2 got resource1!!");
pthread_mutex_unlock(&resource1);
pthread_mutex_unlcok(&resource2);
return 0;
}
int main()
{
pthread _t t1,t2;
pthread_mutex_init(&resource1,NULL);
pthread_mutex_init(&resource2,NULL);
pthread_create(&t1,NULL,process1,NULL);
pthread_create(&t2,NULL,process2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&resource1);
pthread_mutex_destroy(&resource2);