1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | /* * Implementation of Reader-writer problem using openmp * */ #include<stdio.h> #include<omp.h> #include<time.h> omp_lock_t lock; void Reader(int tid) { int a; //Wait till there is lock while (!omp_test_lock(&lock)) { printf("\nReader : %d is waiting ", tid); } omp_unset_lock(&lock); //No need of lock for reading printf("\nReader : %d is reading", tid); sleep(3); } void Writer(int tid) { //First get the lock while (!omp_test_lock(&lock)) { printf("\nWriter : %d is waiting ", tid); } printf("\nWriter : %d acquired lock", tid); printf("\nWriter : %d is writing", tid); //perform operation on the shared data omp_unset_lock(&lock); //release the lock after writing printf("\nWriter : %d released lock", tid); sleep(2); } int main() { int no, tid; omp_init_lock(&lock); srand((unsigned)time(NULL)); int totalthreads; #pragma omp parallel private(tid) shared(totalthreads) { totalthreads = omp_get_num_threads(); while(1) { int randomno = rand() % 100; //Getting thread ID tid = omp_get_thread_num(); // half of threads are readers and half are writers if(randomno < 50) { //calling reader printf("\nProcess no. %d is a reader ", randomno); Reader(randomno); } else { //calling writer printf("\nProcess no. %d is a writer ", randomno); Writer(randomno); } } } } |
Implementation of Reader-Writer problem using OpenMP
Subscribe to:
Posts (Atom)
1 comment:
This is not correct. There is no way for a writer to know whether a reader is accessing the data, so it will proceed to acquire the lock and modify the data, causing potential race conditions.
The usual implementation requires a counter to know how many readers are accessing the critical section.
Post a Comment