条件:5个读者,1个作者
方法:临界区critical_section、读写锁srwlock
#include<iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
SRWLOCK srwlockThread;
CRITICAL_SECTION csThread_out;
unsigned int WINAPI ThreadReaderFunc(LPVOID lp)
{
EnterCriticalSection(&csThread_out);
cout << "The reader ID: " << GetCurrentThreadId() << " start waiting" << endl;
LeaveCriticalSection(&csThread_out);
AcquireSRWLockShared(&srwlockThread);
EnterCriticalSection(&csThread_out);
cout << "The reader ID: " << GetCurrentThreadId() << " start reading" << endl;
LeaveCriticalSection(&csThread_out);
Sleep(rand() % 100);
EnterCriticalSection(&csThread_out);
cout << "The reader ID: " << GetCurrentThreadId() << " end reading" << endl;
LeaveCriticalSection(&csThread_out);
ReleaseSRWLockShared(&srwlockThread);
return 0;
}
unsigned int WINAPI ThreadWriterFunc(LPVOID lp)
{
EnterCriticalSection(&csThread_out);
cout << "The writer start waiting" << endl;
LeaveCriticalSection(&csThread_out);
AcquireSRWLockExclusive(&srwlockThread);
EnterCriticalSection(&csThread_out);
cout << "The writer start writing" << endl;
LeaveCriticalSection(&csThread_out);
Sleep(50);
EnterCriticalSection(&csThread_out);
cout << "The writer end writing" << endl;
LeaveCriticalSection(&csThread_out);
ReleaseSRWLockExclusive(&srwlockThread);
return 0;
}
int main(int argc, char *argv[])
{
InitializeSRWLock(&srwlockThread);
InitializeCriticalSection(&csThread_out);
const int thread_Num = 6;
HANDLE hThread[thread_Num];
hThread[0] = (HANDLE)_beginthreadex(nullptr, 0, ThreadWriterFunc, nullptr, 0, nullptr);
for (int i = 1; i < thread_Num; i++)
{
hThread[i] = (HANDLE)_beginthreadex(nullptr, 0, ThreadReaderFunc, nullptr, 0, nullptr);
}
WaitForMultipleObjects(thread_Num, hThread, true, INFINITE);
for (int i = 0; i < thread_Num; i++)
{
CloseHandle(hThread[i]);
}
DeleteCriticalSection(&csThread_out);
system("pause");
return 0;
}