资源简介
操作系统 读者写者问题c++
代码片段和文件信息
#include
#include
#include
#include
#include
#include
#define MAX_PERSON 100
#define READER 0
#define WRITER 1
#define END -1
#define R READER
#define W WRITER
typedef struct _Person
{
HANDLE m_hThread;
int m_nType;
int m_nStartTime;
int m_nWorkTime;
int m_nID;
}Person;
Person g_Persons[MAX_PERSON];
int g_NumPerson = 0;
long g_CurrentTime = 0;
int g_PersonLists[] = {1W35 2W165 3R52 4W65 5R43 6R177 END};
int g_NumOfReading = 0;
int g_NumOfWriteRequest = 0;
HANDLE g_hReadSemaphore;
HANDLE g_hWriteSemaphore;
bool finished = false;
void CreatePersonList(int *pPersonList);
bool CreateReader(int StartTimeint WorkTimeint ID);
bool CreateWriter(int StartTimeint WorkTimeint ID);
DWORD WINAPI ReaderProc(LPVOID lpParam);
DWORD WINAPI WriterProc(LPVOID lpParam);
int main()
{
g_hReadSemaphore = CreateSemaphore(NULL1100NULL);
g_hWriteSemaphore = CreateSemaphore(NULL1100NULL);
CreatePersonList(g_PersonLists);
printf(“Create all the reader and writer\n ...\n“);
g_CurrentTime = 0;
while(true)
{
g_CurrentTime++;
Sleep(300);
printf(“CurrentTime = %d\n“g_CurrentTime);
if(finished) return 0;
}
}
void CreatePersonList(int *pPersonLists)
{
int i = 0;
int *pList = pPersonLists;
bool Ret;
while(pList[0]!= END)
{
switch(pList[1])
{
case R:
Ret=CreateReader(pList[2]pList[3]pList[0]);
break;
case W:
Ret = CreateWriter(pList[2]pList[3]pList[0]);
break;
}
if(!Ret)
printf(“Create Person %d is wrong\n“pList[0]);
pList += 4;
}
}
DWORD WINAPI ReaderProc(LPVOID lpParam)
{
Person *pPerson = (Person*)lpParam;
while(g_CurrentTime != pPerson->m_nStartTime)
{}
printf(“Reader %d is Requesting ...\n“pPerson->m_nID);
printf(“\n\n******************************************\n“);
WaitForSingleobject(g_hReadSemaphoreINFINITE);
if(g_NumOfReading == 0)
{
WaitForSingleobject(g_hReadSemaphoreINFINITE);
}
g_NumOfReading++;
ReleaseSemaphore(g_hReadSemaphore1NULL);
pPerson->m_nStartTime = g_CurrentTime;
printf(“Reader %d is Reading the Shared Buffer ...\n“pPerson->m_n
- 上一篇:C++实现快速排序
- 下一篇:mfc安装全局钩子,显示窗口的标题
评论
共有 条评论