Question
You must write a C program which will create two threads in your main function inside a while loop. So, your main function would be
You must write a C program which will create two threads in your main function inside a while loop. So, your main function would be something like following:
// global variable
pthread_t tid[2];
int main()
{
int i =0;
While (i<2)
{
//create thread here. Example given below ( not 100% correct??)
//pthread_create(tid[i],NULL,&doSomething,(Fill last argument yourself));
// have to pass i in the last argument, but how ? google is your friend.
//increment i
}
sleep(5);
// waiting for the threads to finish.
return 0;
}
You should also declare your threads which you are passing in the thread creation method as global variables (as done above). So, you can access them in any function.
When you create the threads. You must call a function doSomething using that thread. You have to give the name of the function inside the thread create function call (remember the lecture ?).
Also, you have to pass your counter i to the function of thread (last argument of pthread_create). Inside the function you have to do following things.
1. Check if the current thread is thread 1 or thread 2. Can do that by getting the id of current thread by calling appropriate function (google the function to get the id of a thread). Compare the returned id with the id of thread 1 and thread 2 in an if statement (We studied a function to compare ids of two threads). (Remember you declared your threads as global variable so you can access them in this function)
2. If its the thread 1 then you will print a message saying (I am thread one and the value of i is .. (have to actually show the value here)) you will access the value of i by the parameter received in the function. But the parameter of the function is void pointer. So, you would have to type cast it to integer pointer and then get the actual value by dereferencing the pointer.
3. If its thread 2 then you will print a message saying (I am thread two and the value of i is : (get the value here) )
4. Ideally, for thread one the value of i should be 0 and for thread two the value of i should be 1. Because in your thread create function call you pass i=0 for thread 1 and i=1 for thread 2. But if you run your code a couple of times. You would see this is not the case.
5. Why do you think this is happening? Give reasons.
Submission: You have to submit your .c code. The name of your file should be thread.c. Also at the end of the code write in comments the answer of 5.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started