Question
Write a multi-threaded C program for readers/writers problem using Pthreads. This program should adhere to the following constraints: 1. Multiple readers/writers must be supported (at
Write a multi-threaded C program for readers/writers problem using Pthreads. This program should adhere to the following constraints: 1. Multiple readers/writers must be supported (at least 4 of each type); 2. Readers must read the shared variable multiple times (at least 4 times); 3. Writers must write the shared variable multiple times (at least 4 times); 4. Multiple readers/writers must be supported (at least 4 of each type); Readers must print: a. The reader thread ID, b. The value of the shared variable, c. The number of readers present when value is read;
5. Writers must print: a. The writer thread ID, b. The written value to the shared variable, c. The number of readers present were when value is written. The print out can be implemented using fprintf(). Before a reader/writer attempts to access the shared variable, it should wait some random amount of time. This will help ensure that reads and writes do not occur all at once. For this purpose, you can use srandom() and usleep().
Skeleton Code:
#include
/* GLOBAL SHARED DATA ====================================================== */ unsigned int gSharedValue = 0; pthread_mutex_t gSharedMemoryLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gReadPhase = PTHREAD_COND_INITIALIZER; pthread_cond_t gWritePhase = PTHREAD_COND_INITIALIZER; int gReaders = 0;
void *readerMain(void *threadArgument) {
int id = *((int*)threadArgument);
// reader code
pthread_exit(0); }
void *writerMain(void *threadArgument) {
int id = *((int*)threadArgument);
// writer code
pthread_exit(0); }
// usage of usleep and fprintf // more options can be found using man void sample_code(){
int random_number = random(); int wait_time = random_number % 10; fprintf(stdout, "We are going to wait %d seconds. And the random number is %d. ", wait_time, random_number); // use usleep to make thread sleep // so that reads and writes do not all happen at once usleep(1000000 * wait_time); fprintf(stdout, "Now we are free again. ");
}
int main(int argc, char **argv) { // Seed the random number generator, requied by using random() function srandom((unsigned int)time(NULL));
// comment out the call to sample_code() sample_code();
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started