program in C with one parent thread and two child threads.
Both child threads work on the single global variable sum. Each of
them
implements one for loop, and the for loop is designed to complete
10000 iterations.
• One child thread add 1 to sum in each iteration of the for loop.
starting with 0 and finishing with 10000.
• The other child thread, decrements on 1 the value of sum
in each iteration of the for loop.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep
for details.
#include <pthread.h>
int sum=0;
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
void *myThreadFun(int vargp)
{
if(vargp==2){
for(int i=0;i<10000;i++){
sum=sum+1;
printf("Sum: %d",sum);
}
}
else if(vargp==3){
for(int i=0;i<10000;i++){
sum=sum-1;
printf("Sum: %d",sum);
}
}
}
int main()
{
pthread_t thread_id;
pthread_t thread_id1;
pthread_t thread_id2;
pthread_create(&thread_id, NULL, myThreadFun,1);
pthread_create(&thread_id1, NULL, myThreadFun,2);
pthread_create(&thread_id2, NULL, myThreadFun,3);
pthread_join(thread_id, NULL);
pthread_join(thread_id1, NULL);
pthread_join(thread_id2, NULL);
pthread_exit(NULL);
exit(0);
}
SUMMARY:
The above code implements multithreading in C. 3 threads have been created as parent, child1 and child2. We pass 1,2 and 3 as argument to the function while creating the thread. If the thread executing the function is 2 than it increments the global variable sum and if the thread executing is 3 than it decrements the global variable sum. The parent thread does not perform any function as it was not instructed.
Note: If you have any queries than let me know in the comments. If you find it helpful then a Like would be appreciated
Get Answers For Free
Most questions answered within 1 hours.