Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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

Systems Analysis And Synthesis Bridging Computer Science And Information Technology

Authors: Barry Dwyer

1st Edition

0128054492, 9780128054499

More Books

Students also viewed these Databases questions

Question

What is the most important part of any HCM Project Map and why?

Answered: 1 week ago