任务5- 事件对象解决读写者问题
- 格式:doc
- 大小:67.00 KB
- 文档页数:7
1.基本信息
➢实践题目:事件对象实现P、V操作并解决读写者问题
➢完成人:
班级:07062301
姓名:陈杨
学号:0706230101
➢报告日期:2011年1月5日
2.实践内容简要描述
➢实践目标
1.掌握事件对象的使用方法
2. 理解P、V操作的内部机制及读者-写者问题的实现方法。
➢实践内容
用Win32提供的同步对象实现P、V操作,并使用它们解决读者-写者问题
利用事件机制模拟多值信号量。算法如下:
binary-semaphore S1, S2; // initializtion: S1 = 1, S2 = 0
int C; // initializtion: the count of recource
wait():
Wait(S1);
C--;
if(C < 0) {
signal(S1);
wait(S2);
}
signal(S2);
signal():
wait(S1);
C++;
if(C <= 0) {
signal(S2);
}
else {
signal(S1);
}
读者-写者问题算法如下:
Writer:
wait(Wmutex);
// do writing
signal(Wmutex);
Reader:
wait(Rmutex);
if(Rcount == 0) {
wait(Wmutex);
}
Rcount++;
signal(Rmutex);
// do reading
wait(Rmutex);
Rcount--;
if(Rcount == 0) {
signal(Wmutex);
}
signal(Rmutex);
➢设计思路
利用事件对象实现P、V操作
➢主要数据结构
int readcount = 0;
int writecount = 0;
struct MySemaphore
{
HANDLE s1, s2;
int c;
};
MySemaphore ReaderS;
MySemaphore WriterS;
struct ThreadInfo
{
int serial;
char entity;
double delay;
double persist;
};
➢主要代码结构及分析
///////////////////////////////////////////////////////////////
// Reader Priority fuction
// file: filename
//////////////////////////////////////////////////////////////
void ReaderPriority( char* file )
{
DWORD n_thread = 0;
DWORD thread_ID;
DWORD wait_for_all;
initMySemaphore(&ReaderS,1);
initMySemaphore(&WriterS,1);
readcount = 0; //init readercount
// Tread Object Array
HANDLE h_Thread[MAX_THREAD_NUM];
ThreadInfo thread_info[MAX_THREAD_NUM];
ifstream inFile;
inFile.open(file); //open file
printf( "Reader Priority:\n\n" );
while ( inFile )
{
// read every reader/writer info
inFile>>thread_info[n_thread].serial;
inFile>>thread_info[n_thread].entity;
inFile>>thread_info[n_thread].delay;
inFile>>thread_info[n_thread++].persist;
inFile.get();
} //end while
inFile.close();
for( int i = 0; i < (int)(n_thread); i++)
{
if(thread_info[i].entity == 'R' || thread_info[1].entity == 'r')
{
// Create Reader thread
h_Thread[i] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)(RP_ReaderThread), &thread_info[i], 0, &thread_ID);
}
else {
// Create Writer thread
h_Thread[i] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)(RP_WriterThread), &thread_info[i], 0, &thread_ID);
}
} //end for
// waiting all thread will been finished