Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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);
}
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Handbook Of Relational Database Design

Authors: Candace C. Fleming, Barbara Von Halle

1st Edition

0201114348, 978-0201114348

More Books

Students also viewed these Databases questions