Question
Write a program with one thread function, define an array with 5 elements as a global variable [ use the code below ] Call the
- Write a program with one thread function, define an array with 5 elements as a global variable [ use the code below ]
- Call the thread 2 times
- First for incrementing the array elements by 2.
- Second for incrementing the array elements by 3.
- Give a "sleep(2)" in the for loop of the thread function to model some process happening in between.
- Check if you are getting an expected output of incremented array elements.
Identify the critical section
Avoid the critical section using a mutex
Write a tutorial explaining the code
#include
#include
#include
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int arr[5];
void *incr(int n) {
// Complete the code here
}
int main() {
pthread_t t1, t2;
int i;
for(i=0;i<5;i++)
{
arr[i]=1;
}
pthread_create(); //Complete thread creation to pass the value to be incremented in thread 1
pthread_create(); //Complete thread creation to pass the value to be incremented in thread 2
pthread_join(t1,NULL);
pthread_join(t2,NULL);
exit(0);
}
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