Consider the following code: #include <stdio.h> #include <unistd.h> #include <pt
ID: 3919556 • Letter: C
Question
Consider the following code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *my_function(void *param);
int main()
{
int i;
pthread_t tid;
pid_t pid;
for(i=0; i<3; i++) {
pid = fork();
pthread_create(&tid,NULL,my_function,NULL);
pthread_join(tid,NULL);
}
}
a. Explain what is happening within the for-loop. Your ex- planation must explain the
purpose and effect of the three system calls.
b. Including the initial parent process, how many processes are created. (To answer this
question do not supply just the number of processes—explain your reasoning).
Note: the answer is not 4.
c. How many unique threads are created? (To answer this ques- tion do not supply just the number
of threads—explain your reasoning. Also remember, the initial process is thread 1).
Explanation / Answer
a) Inside the For Loop
pid=fork();
fork() System call is called to create a new child process and the new child process id is store in a name of variable pid .
Pid variable is a variable that is of type pid_t, Pid_t d=generally keeps process id.
pthread_create(&tid,NULL,my_function,NULL);
we call pthread_create() function to create a thread.
pthread_create() takes 4 arguments.
The first argument is a pointer to thread_id which is set by this function.
The second argument specifies attributes. If the value is NULL, then default attributes shall be used.
The third argument is name of function to be executed for the thread to be created.
The fourth argument is used to pass arguments to thread.
pthread_join(tid,NULL);
The pthread_join() function for threads is the equivalent of wait() for processes. A call to pthread_join blocks the calling thread until the thread with identifier equal to the first argument terminates .
b. fork() is called 3 times by using for() loop.
1st fork() create a child process which runs cuncurrently with parent
2nd fork() is run both in parent and 1st child. which concurrently run with 2 above parent
3rd fork() is executed by total 4 processes.
In Simple way it is like Complete binart tree ,with height no. of fork()-1.
So total Process created can be calculated as 2no.of fork() .In this case 23 = 8.
(c) pthread_create(); creates a new thread(lightweight process) in a main process.
as we just came to know that there are 8 process has been created and each process will call the function pthread_create().So total 8 thread will be created.
The pthread_join() function for threads is the equivalent of wait() for processes. A call to pthread_join blocks the calling thread until the thread with identifier equal to the first argument terminates.
Hope You Like It :-)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.