读者-写者问题
使用互斥量和信号量解决读者-写者问题,程序中设置1个写者进程,5个读者进程。
#include<stdio.h>
#include<process.h>
#include<windows.h>
#define READER_NUM 5
CRITICAL_SECTION g_cs,g_cs_writer_count;
HANDLE g_hEventWriter,g_hEventNoReader;
int g_nReaderCount;
void ReaderPrintf(char *pszFormat,...)
{
va_list pArgList;
va_start(pArgList,pszFormat);
EnterCriticalSection(&g_cs);
vfprintf(stdout,pszFormat,pArgList);
LeaveCriticalSection(&g_cs);
va_end(pArgList);
}
unsigned int __stdcall ReaderThreadFun(PVOID pM)
{
ReaderPrintf("编号为%d的读者进入等待中...\n",GetCurrentThreadId());
WaitForSingleObject(&g_hEventWriter,INFINITE);
EnterCriticalSection(&g_cs_writer_count);
g_nReaderCount++;
if(g_nReaderCount==1)
{
ResetEvent(g_hEventNoReader);
}
LeaveCriticalSection(&g_cs_writer_count);
ReaderPrintf("编号为%d的读者开始读取文件...\n",GetCurrentThreadId());
Sleep(rand()%100);
ReaderPrintf("编号为%的读者结束读取文件\n",GetCurrentThreadId());
EnterCriticalSection(&g_cs_writer_count);
g_nReaderCount--;
if(g_nReaderCount==0)
SetEvent(g_hEventNoReader);
LeaveCriticalSection(&g_cs_writer_count);
return 0;
}
void WriterPrintf(char *pszStr)
{
EnterCriticalSection(&g_cs);
printf("%s\n",pszStr);
LeaveCriticalSection(&g_cs);
}
unsigned int __stdcall WriterThreadFun(PVOID pM)
{
WriterPrintf("---写者线程进入等待中...");
WaitForSingleObject(g_hEventNoReader,INFINITE);
ResetEvent(g_hEventWriter);
WriterPrintf("---写者开始写文件.....");
Sleep(rand()%100);
WriterPrintf("---写者结束写文件.....");
SetEvent(g_hEventWriter);
return 0;
}
int main()
{
int i;
HANDLE hThread[READER_NUM+1];
printf("\t读者写者问题\n");
InitializeCriticalSection(&g_cs);
InitializeCriticalSection(&g_cs_writer_count);
g_hEventWriter=CreateEvent(NULL,TRUE,TRUE,NULL);
g_hEventNoReader=CreateEvent(NULL,FALSE,TRUE,NULL);
g_nReaderCount=0;
for(i=1;i<=2;i++)
hThread[i]=(HANDLE)_beginthreadex(NULL,0,ReaderThreadFun,NULL,0,NULL);
hThread[0]=(HANDLE)_beginthreadex(NULL,0,WriterThreadFun,NULL,0,NULL);
Sleep(50);
for(;i<=READER_NUM;i++)
hThread[i]=(HANDLE)_beginthreadex(NULL,0,ReaderThreadFun,NULL,0,NULL);
WaitForMultipleObjects(READER_NUM+1,hThread,TRUE,INFINITE);
for(i=0;i<READER_NUM+1;i++)
CloseHandle(hThread[i]);
CloseHandle(g_hEventWriter);
CloseHandle(g_hEventNoReader);
DeleteCriticalSection(&g_cs);
DeleteCriticalSection(&g_cs_writer_count);
Sleep(5000);
return 0;
}
动态测试系统内存
#include<windows.h>
#include<stdio.h>
#define DIV 1024
char *divisor="K";
void main()
{
MEMORYSTATUS stat;
GlobalMemoryStatus(&stat);
printf("MEMORYSTATUS 结构体长度 %1d bites \n",stat.dwLength);
printf("已使用物理内存百分比 %1d %% \n",stat.dwMemoryLoad);
printf("总物理内存 %1d%s bytes \n",stat.dwTotalPhys/DIV,divisor);
printf("可用物理内存 %1d%s bytes \n",stat.dwAvailPhys/DIV,divisor);
printf("总页面文件数 %1d%s bytes \n",stat.dwTotalPageFile/DIV,divisor);
printf("可用页面文件数 %1d%s bytes \n",stat.dwAvailPageFile/DIV,divisor);
printf("总虚拟内存 %1d %s bytes \n",stat.dwTotalVirtual/DIV,divisor);
printf("可用虚拟内存 %1d%s bytes \n",stat.dwAvailVirtual/DIV,divisor);
Sleep(10000);
}