//---------------------------------------------
//program : 本程序用来演示读者写者的线程同步问题
//author : dspeeding
//date : 2009.11.19
//---------------------------------------------
#include <TCHAR.h>
#include <stdio.h>
#include <windows.h>
#include <process.h>
#define LEN sizeof(Node)
#define MAX_THREAD_NUM 32
typedef struct node
{
int ThreadNum; //线程编号
char Type; //读写者标志位
float BeginTime; //线程开始时间
float RunTime; //线程运行时间
}Node,*lpNode;
FILE *fp; //文件指针
Node ThreadNode[MAX_THREAD_NUM]; //线程信息数组
DWORD SumNum=0; //记录线程总数
int Rcount=0; //读者数
int Wcount=0; //写者数
SYSTEMTIME time; //时间
//------------------读者优先-读者处理函数------------------
void RF_RThreadProc(LPVOID lpParam)
{
HANDLE wMutex,rMutex;
int id=((lpNode)lpParam)->ThreadNum;
double starttime=(double)((lpNode)lpParam)->BeginTime;
double runtime=(double)((lpNode)lpParam)->RunTime;
SYSTEMTIME CurrentTime;
int OutputTime;
wMutex=OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,_T("WCounter"));
rMutex=OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,_T("RCounter"));
Sleep((DWORD)(starttime*1000));
GetLocalTime(&CurrentTime);
OutputTime=CurrentTime.wSecond-time.wSecond;
if(OutputTime<=0) OutputTime+=60;
printf("Time :%2d s 线程 %d 发出申请读操作\n",OutputTime,id);
WaitForSingleObject(rMutex,INFINITE);
++Rcount;
if(Rcount==1)
WaitForSingleObject(wMutex,INFINITE);
ReleaseSemaphore(rMutex,1,NULL);
GetLocalTime(&CurrentTime);
OutputTime=CurrentTime.wSecond-time.wSecond;
if(OutputTime<=0) OutputTime+=60;
printf("Time :%2d s 线程 %d 开始读操作\n",OutputTime,id);
Sleep((DWORD)(runtime*1000));
GetLocalTime(&CurrentTime);
OutputTime=CurrentTime.wSecond-time.wSecond;
if(OutputTime<=0) OutputTime+=60;
printf("Time :%2d s 线程 %d 结束读操作\n",OutputTime,id);
WaitForSingleObject(rMutex,INFINITE);