/********************************************************** File: reader_writer.cc Description: A program that simulates the reader_writer model for accessing a database. Author: Dana Vrajitoru Organization: IUSB Date: December 2, 2002. ***********************************************************/ #include #include #include #include #include // Global variables int database = 0; int writer_nr = 0, waiting = 0, reader_nr=0; pthread_mutex_t mutex, barrier_mutex; const int NR_WCYCLES = 3, NR_RCYCLES = 10; pthread_cond_t condition; // Prototypes void *Writer(void *ignored); void *Reader(void *ignored); void Read(); void Write(); void Create_threads(pthread_t *thread, int no_threads, void*(*function)(void*), void *arg); // Waits for a random amount fo time between two limits. void Wait(int low, int high); // Waits for a random and relatively large amount of time. void Long_wait(); // Waits for a random and relatively short amount of time. void Short_wait(); void Initialize_all(); void Barrier(int thread_nr); int main() { int rnr, wnr, tnr; srand(time(NULL)); Initialize_all(); printf("Enter the number of readers\n"); scanf("%d", &rnr); printf("Enter the number of writers\n"); scanf("%d", &wnr); tnr = rnr + wnr; pthread_t *readers = new pthread_t[rnr]; Create_threads(readers, rnr, Reader, (void *) (&tnr)); pthread_t *writers = new pthread_t[wnr]; Create_threads(writers, wnr, Writer, (void *) (&tnr)); pthread_exit(NULL); } // Initializes all of the global mutex and condition variables. void Initialize_all() { pthread_mutex_init(&mutex, NULL); pthread_mutex_init(&barrier_mutex, NULL); pthread_cond_init(&condition, NULL); } // Creates several threads with the same function and argument. void Create_threads(pthread_t *thread, int nr_threads, void*(*function)(void*), void *arg) { for (int i=0; i