Question: I think my code is complete i would like some advise thoguh. #include #include #include #define NUM _ THREADS 2 #define COUNT _ LIMIT 2

I think my code is complete i would like some advise thoguh.
#include
#include
#include
#define NUM_THREADS 2
#define COUNT_LIMIT 2000000
typedef struct {
int value;
pthread_mutex_t lock;
} Counter;
Counter counter ={0, PTHREAD_MUTEX_INITIALIZER};
int thread1_bonus_count =0;
void *increment_counter_thread1(void *arg){
int i =0;
while (i COUNT_LIMIT){
pthread_mutex_lock(&counter.lock); // Entry Section
if (counter.value %100==0){
counter.value +=100; // Critical Section
thread1_bonus_count++;
} else {
counter.value++; // Critical Section
}
pthread_mutex_unlock(&counter.lock); // Exit Section
i++;
}
// Remainder Section
printf("I'm thread1, I did %d updates and I got the bonus for %d times, counter =%d
", i, thread1_bonus_count, counter.value);
pthread_exit(NULL);
}
void *increment_counter_thread2(void *arg){
int i =0;
while (i COUNT_LIMIT){
pthread_mutex_lock(&counter.lock); // Entry Section
counter.value++; // Critical Section
pthread_mutex_unlock(&counter.lock); // Exit Section
i++;
}
// Remainder Section
printf("I'm thread2, I did %d updates, counter =%d
", i, counter.value);
pthread_exit(NULL);
}
int main(){
pthread_t threads[NUM_THREADS];
if (pthread_create(&threads[0], NULL, increment_counter_thread1, NULL)!=0){
perror("Failed to create thread1");
exit(EXIT_FAILURE);
}
if (pthread_create(&threads[1], NULL, increment_counter_thread2, NULL)!=0){
perror("Failed to create thread2");
exit(EXIT_FAILURE);
}
for (int i =0; i NUM_THREADS; i++){
if (pthread_join(threads[i], NULL)!=0){
perror("Failed to join thread");
exit(EXIT_FAILURE);
}
}
printf("From parent, counter =%d
", counter.value);
if (pthread_mutex_destroy(&counter.lock)!=0){
perror("Failed to destroy mutex");
exit(EXIT_FAILURE);
}
pthread_exit(NULL);
}
 I think my code is complete i would like some advise

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!