参考http://en.wikipedia.org/wiki/Readers-writers_problem
第二类读者写者问题,写优先
#include <cstdio> #include <Windows.h> #include <ctime> int readcount, writecount; HANDLE mutex_1; // 限制readcount HANDLE mutex_2; // 限制writecount HANDLE mutex_3; // 限制r HANDLE r; // 有没有reader HANDLE w; // 有没有writer /*能够并发地读,不能并发地写,写的时候不能读,写优先*/ DWORD WINAPI reader_thread(void *param); DWORD WINAPI writer_thread(void *param); DWORD WINAPI reader_thread(void * param) { int my_id = *(int *)param; printf("%dth reader come\n", my_id); WaitForSingleObject(mutex_3, INFINITE); WaitForSingleObject(r,INFINITE); WaitForSingleObject(mutex_1, INFINITE); readcount += 1; if(readcount == 1) WaitForSingleObject(w, INFINITE);//只要有reader已经在read,就不让一个write去写 ReleaseMutex(mutex_1); ReleaseMutex(r); ReleaseMutex(mutex_3); /*reading*/ printf("%dth reader is doing reading\n", my_id); Sleep(2000); printf("%dth reader finish reading\n", my_id); WaitForSingleObject(mutex_1, INFINITE); readcount -= 1; if (readcount == 0) ReleaseMutex(w); ReleaseMutex(mutex_1); return 1; } DWORD WINAPI writer_thread(void *param) { int my_id = *(int *)param; printf("%dth writer come\n", my_id); WaitForSingleObject(mutex_2, INFINITE); writecount += 1; if(writecount == 1) WaitForSingleObject(r, INFINITE);//只要有writer存在,就reader在后面等待 ReleaseMutex(mutex_2); WaitForSingleObject(w, INFINITE); printf("%dth writer is writing\n", my_id); Sleep(2000); printf("%dth writer finish writing\n", my_id); WaitForSingleObject(mutex_2, INFINITE); writecount -= 1; if(writecount == 0) ReleaseMutex(r); ReleaseMutex(mutex_2); return 1; } #define NUM 100000 int reader_id,writer_id; int temp_r[NUM], temp_w[NUM]; void gen() { HANDLE h; if(rand()%2==0) // 产生reader { reader_id++; temp_r[reader_id] = reader_id; h = CreateThread(NULL, 0, reader_thread, (void *)(&temp_r[reader_id]), 0, NULL); } else // 产生writer { writer_id++; temp_w[writer_id] = writer_id; h = CreateThread(NULL, 0, writer_thread, (void *)(&temp_w[writer_id]), 0, NULL); } } int main () { mutex_1 = CreateMutex(NULL, FALSE, L"mutex_1"); mutex_2 = CreateMutex(NULL, FALSE, L"mutex_2"); mutex_3 = CreateMutex(NULL, FALSE, L"mutex_3"); r = CreateMutex(NULL, FALSE, L"r"); w = CreateMutex(NULL, FALSE, L"w"); srand(time(NULL)); while(reader_id<NUM && writer_id<NUM) { if(rand()%2 == 0) { gen(); } if(rand()%3 == 0) { gen(); } if(rand()%3 == 0) { gen(); } Sleep(3000); } return 0; }