Question: So while showing racing condition, can I also show reader - writer problem or producer - consumer problem? Below is the example code for racing

So while showing racing condition, can I also show reader-writer problem or producer-consumer problem?
Below is the example code for racing condition:
#include
#include
#include
#define NUM_PRINTERS 5// Number of printers
#define NUM_USERS 10// Number of users
int printers[NUM_PRINTERS]; // Printers array: 0 means available, 1 means in use
// Thread function to simulate a user trying to use a printer
void *user_function(void *arg){
int user_id =*(int *)arg;
// Each thread will loop to find an available printer
for (int i =0; i < NUM_PRINTERS; i++){
if (printers[i]==0){// Check if printer is available
printf("User %d: Found printer %d available.
", user_id, i +1);
usleep(10000); // Simulate delay, making race condition more likely
printers[i]=1; // Mark printer as in use
printf("User %d: Using printer %d.
", user_id, i +1);
usleep(50000); // Simulate time taken to use printer
printers[i]=0; // Release printer
printf("User %d: Finished using printer %d.
", user_id, i +1);
break;
}
}
return NULL;
}
int main(){
pthread_t threads[NUM_USERS];
int user_ids[NUM_USERS];
// Initialize printers
for (int i =0; i < NUM_PRINTERS; i++){
printers[i]=0; // Set all printers as available
}
// Create threads for each user
for (int i =0; i < NUM_USERS; i++){
user_ids[i]= i +1;
pthread_create(&threads[i], NULL, user_function, &user_ids[i]);
}
// Wait for all threads to complete
for (int i =0; i < NUM_USERS; i++){
pthread_join(threads[i], NULL);
}
return 0;
}

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 Programming Questions!