Problem definition:
Existing piece of shared memory, multiple read processes, and multiple write processes. Multiple read processes can be read at the same time, but no other read or write processes are executed when there is a write process in progress.
There are 3 variants of the problem. The first is called "Reader First" (readers-preference). In this case, as long as there is a process in the read, the write process has to wait.
The implementation is as follows:
#include <stdio.h>#include<stdlib.h>#include<pthread.h>#defineM 6//Number of readers#defineN 2//Number of writersintReadcount =0;//Current number of readerspthread_mutex_t mutex = Pthread_mutex_initializer;//for mutually exclusive modifications to the Readcount variablepthread_mutex_t RW = pthread_mutex_initializer;//for mutual exclusion between reading, writing, and writing and writingvoid* Write (void*Arg) {Pthread_mutex_lock (&rw); printf ("writer%d is writing\n", ARG); Sleep (1); printf ("writer%d is leaving\n", ARG); Pthread_mutex_unlock (&rw);}void* Read (void*Arg) {Pthread_mutex_lock (&mutex); if(Readcount = =0) Pthread_mutex_lock (&rw); ++Readcount; Pthread_mutex_unlock (&mutex); printf ("Reader%d is reading\n", ARG); Sleep (1); printf ("Reader%d is leaving\n", ARG); Pthread_mutex_lock (&mutex); --Readcount; if(Readcount = =0) Pthread_mutex_unlock (&rw); Pthread_mutex_unlock (&mutex);}intMain () {pthread_t readers[m], writers[n]; inti; for(i =0; i < M; ++i) pthread_create (&readers[i], NULL, read, (void*) (i); for(i =0; i < N; ++i) pthread_create (&writers[i], NULL, write, (void*) (i); Sleep (Ten); return 0;}
In this case, it is easy to cause the writer to starve.
Reader writer problem of multi-thread synchronization