You are on page 1of 7

Operating System Lab

Roll No # 16F-8286
Section 6A
Lab No # 08
Joun Habib
Question no # 01:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void * thread1()
{
int c=0;
while(c++ < 500)
printf("Hello !!\n");
}
void * thread2()
{
int c=0;
while(c++ < 500)
printf("How are you !!\n");
}
int main ()
{
int status;
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,thread1,NULL);
pthread_create(&tid2,NULL,thread2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
i)
Pthread_Create allow us to sepreate certain parallelized tasks inyo separate threads. It will run the two
statements simultaneously.

Pthread_join is used when threads wait for another one to finish. The two threads work in parallel, then
they must combine the results they obtained.
ii)
Hello will be printed 500 times on screen and thread1 will print it.
iii)
How Are You Will be printed 500 times and thread2 will print it.
iv)
Because the thread is a process in which process are divided into sub parts so according to that every
process will separately with its own limit of code. As Hello and How are you are two different threads so
they will not run consecutively as they are two different processes. This is just because of context
switching.
v)

It will increase the count of thread2 two times.


Question No # 02
#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

int count=0,result=0;

void * thread1()

count++;

result+=count;

void * thread2()
{

count++;

result+=count;

void * thread3()

count++;

result+=count;

int main ()

int status;

pthread_t tid1,tid2,tid3,tid4;

pthread_create(&tid1,NULL,thread1,NULL);

pthread_create(&tid2,NULL,thread2,NULL)

pthread_create(&tid3,NULL,thread3,NULL);

pthread_join(tid1,NULL);

pthread_join(tid2,NULL);

pthread_join(tid3,NULL);

printf("\n\nCount:%d \nResult : %d \n",count,result);

return 0;

}
Question No # 03
#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

pthread_t * thread()

pthread_t pthread_self();

return pthread_self();

int main ()

int status;

pthread_t tid[4];

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

{
pthread_create(&tid[i],NULL,thread,NULL);

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

pthread_join(tid[i],NULL);

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

printf("\n thread id of t%d = %d and process id=%d\n",i+1,tid[i],getpid());

return 0;

You might also like