多线程同步之读者写者问题
问题定义:
现有一块共享内存,多个读进程和多个写进程。多个读进程可以同时读,但是当有一个写进程正在写时,其他任何读进程或写进程都不能执行。
该问题有3种变种。第一种称为“读者优先”(readers-preference)。在此情况下,只要有进程在读,写进程就得等待。
实现如下:
#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 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //用于互斥地修改readCount变量 pthread_mutex_t rw = PTHREAD_MUTEX_INITIALIZER; //用于读、写以及写、写之间的互斥 void* 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); } 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; }
这种情况下,容易造成写者饿死现象。