Question: In C! Can you please help me edit this code a little bit. I only want the first thread to have the bonus mutex, and

In C!

Can you please help me edit this code a little bit. I only want the first thread to have the bonus mutex, and the other 2 to only update and not use the bonus.

#include

#include

#include

#include

#define NUM_THREADS 3

#define COUNT_LIMIT 2000000

int counter = 0;

int bonus = 0;

// Declare the semaphores

sem_t mutex;

sem_t bonus_mutex;

void *count(void *t) {

int tid = *(int*)t;

int i, count;

for (i = 0; i < COUNT_LIMIT; i++) {

// Entry section

sem_wait(&mutex);

// Critical section

counter++;

if (counter % 1000 == 0) {

bonus++;

sem_wait(&bonus_mutex);

sem_post(&bonus_mutex);

}

// Exit section

sem_post(&mutex);

}

// Remainder section

printf("Im thread%d, I did %d updates and I got the bonus for %d times, counter = %d ", tid, COUNT_LIMIT, bonus, counter);

pthread_exit(NULL);

}

int main(int argc, char *argv[]) {

pthread_t threads[NUM_THREADS];

int thread_args[NUM_THREADS];

int rc, t;

// Initialize the semaphores

sem_init(&mutex, 0, 1);

sem_init(&bonus_mutex, 0, 1);

// Create the threads

for (t = 0; t < NUM_THREADS; t++) {

thread_args[t] = t+1;

rc = pthread_create(&threads[t], NULL, count, (void*)&thread_args[t]);

if (rc) {

printf("ERROR; return code from pthread_create() is %d ", rc);

exit(-1);

}

}

// Wait for the threads to finish

for (t = 0; t < NUM_THREADS; t++) {

rc = pthread_join(threads[t], NULL);

if (rc) {

printf("ERROR; return code from pthread_join() is %d ", rc);

exit(-1);

}

}

// Remainder section

printf("from parent counter = %d ", counter);

// Destroy the semaphores

sem_destroy(&mutex);

sem_destroy(&bonus_mutex);

pthread_exit(NULL);

}

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!