Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

NAME : ABDUL SABOOR

ROLL NUMBER : SP18-BCS-017]


ASSIGNMENT OS

EXAMPLE 1 :

#include<iostream>

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

using namespace std;

sem_t mutex;

void* thread(void* arg) { //wait

sem_wait(&mutex);

cout<<"\nEntered..\n";

//critical section

sleep(4); //signal

cout<<"\nJust Exiting...\n";

sem_post(&mutex);

}
int main()

sem_init(&mutex, 0, 1); //("Name semophore",0 for thread 1 for process,usigned


int vale assignmnt to mutex)

pthread_t t1,t2;

pthread_create(&t1,NULL,thread,NULL); //(id,null,function,argument)

sleep(2);

pthread_create(&t2,NULL,thread,NULL);

pthread_join(t2,NULL);

sem_destroy(&mutex);

return 0;

OUTPUT :

EXAMPLE 2 :
#include<iostream>

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

using namespace std;

char buff[20];

sem_t mutex;

void* thread1(void* arg)

{ //wait

sem_wait(&mutex);

cout<<"\nEntered..\n";

//critical section

sleep(4);

cout<<"\nThread1..\n";

sprintf(buff, "%s", "Hello BCS"); //we can use loop here

//signal

cout<<"\nJust Exiting...\n";

sem_post(&mutex);

void* thread2(void* arg) {


//wait

sem_wait(&mutex);

cout<<"\nEntered..\n";

//critical section

sleep(4);

cout<<"\nThread2..\n";

cout<<buff;

//signal

cout<<"\nJust Exiting...\n";

sem_post(&mutex);

int main()

sem_init(&mutex, 0, 1); //initiliazing thread

pthread_t t1,t2;

pthread_create(&t1,NULL,thread1,NULL); //creating thread

sleep(2);

pthread_create(&t2,NULL,thread2,NULL);

pthread_join(t1,NULL);

pthread_join(t2,NULL);

sem_destroy(&mutex);
return 0;

OUTPUT :
LAB ASSIGNMENT :

#include<iostream>

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

#include <stdlib.h>

#include <time.h>

using namespace std;

char buff[20];

sem_t mutex;

int random[20];

void* thread1(void* arg)

{ //wait

sem_wait(&mutex);

cout<<"\nEntered..\n";

//critical section

sleep(4);

cout<<"\nThread1..\n";

srand (time(0));
cout<<"Random numbers"<<endl;

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

random[i]=rand()%20+1;

cout<<random[i]<<" ";

//cout<<"\nJust Exiting...\n";

sem_post(&mutex);

void* thread2(void* arg) {

//wait

sem_wait(&mutex);

//cout<<"\nEntered Thread 2..\n";

//critical section

cout<<endl;

sleep(4);

cout<<"Sqaure"<<endl;
for(int i=0;i<20;i++)

cout<<(random[i]*random[i])<<" ";

//signal

cout<<"\nJust Exiting...\n";

sem_post(&mutex);

int main()

sem_init(&mutex, 0, 1); //initiliazing thread

pthread_t t1,t2;

pthread_create(&t1,NULL,thread1,NULL); //creating thread

sleep(2);

pthread_create(&t2,NULL,thread2,NULL);

pthread_join(t1,NULL);

pthread_join(t2,NULL);

sem_destroy(&mutex);
return 0;

OUTPUT:

You might also like