/* Requirements:
Priority Readers and Writers
Write a multi-threaded C program that gives readers priority over writers concerning a shared (global) variable. Essentially, if any readers are waiting, then they have priority over writer threads -- writers can only write when there are no readers. This program should adhere to the following constraints:
Multiple readers/writers must be supported (5 of each is fine)
Readers must read the shared variable X number of times
Writers must write the shared variable X number of times
Readers must print:
The value read
The number of readers present when value is read
Writers must print:
The written value
The number of readers present were when value is written (should be 0)
Before a reader/writer attempts to access the shared variable it should wait some random amount of time
Note: This will help ensure that reads and writes do not occur all at once
Use pthreads, mutexes, and condition variables to synchronize access to the shared variable
*/
#include <pthread.h>
#include <iostream>
#include <vector>
#include <random>
#include <unistd.h>
using std::cout;
using std::endl;
using std::vector;
#define print(a) cout<<a<<endl;
#define NUM_ITERATION 5
int data = 11;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_reader = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_writer = PTHREAD_COND_INITIALIZER;
int num_reader = 0;
int num_writer = 0;
std::random_device rand_device;
void* Reader(void* param);
void* Writer(void* param);
int main(int argc, char* argv[]){
pthread_t Readers[5];
pthread_t Writers[5];
long i;
for(i=0; i<5; ++i){
pthread_create(&Readers[i],NULL,Reader,(void*)i);
pthread_create(&Writers[i],NULL,Writer,(void*)i);
}
for(i=0; i<5; ++i){
pthread_join(Readers[i],NULL);
pthread_join(Writers[i],NULL);
}
return 0;
}
void* Reader(void* param){
long name = (long) param;
for (int i=0; i<NUM_ITERATION; ++i){
usleep(300+rand_device()%300);
pthread_mutex_lock(&m);
// while(num_writer>0){
// pthread_cond_wait(&c_writer,&m);
// }
++num_reader;
print("reader #"<<name<<" gets:"<<data<<", along with other "<<(num_reader-1)<<" readers.");
pthread_mutex_unlock(&m);
--num_reader;
if (num_reader == 0){
pthread_cond_signal(&c_reader);
}
}
pthread_exit(0);
}
void* Writer(void* param){
long name = (long) param;
for (int i=0; i<NUM_ITERATION; ++i){
usleep(300+rand_device()%300);
pthread_mutex_lock(&m);
while(num_reader>0){
pthread_cond_wait(&c_reader,&m);
}
++num_writer;
data = rand_device()%90 + 10;
print("writer #"<<name<<" changes data to "<<data<<", along with "<<num_reader<<" readers.");
pthread_mutex_unlock(&m);
--num_writer;
// if(num_writer == 0){
// pthread_cond_signal(&c_writer);
// }
}
pthread_exit(0);
}