Problem Definition:
An existing shared memory, multiple processes and multiple read-write process. Read more processes can be read at the same time, but when there is a write process is writing, any other process to read or write process can not be executed.
The problem has three variants. The first is called "Reader Priority" (readers-preference). In this case, as long as there is progress in reading and writing process would have to wait.
To achieve the following:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define M. 6 // Number of Readers #define N 2 // Number of Writers int ReadCount = 0 ; // Current Number of Readers the mutex = PTHREAD_MUTEX_INITIALIZER pthread_mutex_t; // for modifying readCount mutex variable pthread_mutex_t RW = PTHREAD_MUTEX_INITIALIZER; // for reading, writing and writing are mutually exclusive write void * write ( void * Arg) { the 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); } int main() { pthread_t readers[M], writers[N]; int i; 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(10); return 0; }
In this case, likely to cause the phenomenon of writer starvation.
Reproduced in: https: //www.cnblogs.com/gattaca/p/4734590.html