当前位置:首页 > 操作系统原理实验报告
种同步对象和相应的系统调用,用于线程的互斥与同步。通过对读者写者问题的调试,了解Windows2000/XP中的同步机制。 五、源代码
#include \#include
#define READER 'R' #define WRITER 'W' #define INTE_PER_SEC 1000 #define MAX_THREAD_NUM 64 #define MAX_FILE_NUM 32 #define MAX_STR_LEN 32
int readcount=0; int writecount=0;
CRITICAL_SECTION RP_Write; CRITICAL_SECTION cs_Write; CRITICAL_SECTION cs_Read; struct ThreadInfo {
int serial; char entity; double delay; double persist;
// 读者 // 写者
// 每秒时钟中断数目。 // 最大线程数目 // 最大数据文件数目 // 字符串长度 // 读者数目 // 写者数目 //临界区 // 线程序号
//线程类别(判断读者线程还是写者线程)
};
/////////////////////////////////////////////////////////////////////////// // 读者优先--读者线程 //p:读者线程信息
void RP_ReaderThread(void* p) {
//互斥变量 HANDLE h_Mutex;
h_Mutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,\
DWORD wait_for_mutex; //等待互斥变量所有权 DWORD m_delay; // 延迟时间 DWORD m_persist; // 读文件持续时间 int m_serial; //线程序号 //从参数中获得信息
m_serial=((ThreadInfo*)(p))->serial;
m_delay=(DWORD)(((ThreadInfo*)(p))->delay*INTE_PER_SEC); m_persist=(DWORD)(((ThreadInfo*)(p))->persist*INTE_PER_SEC); Sleep(m_delay); //延迟等待
printf(\
// 等待互斥信号,保证对readcount的访问、修改互斥 wait_for_mutex=WaitForSingleObject(h_Mutex,-1); //读者数目增加
Readcount++; if(readcount==1) {
//第一个读者,等待资源 EnterCriticalSection(&RP_Write); }
ReleaseMutex(h_Mutex); //释放互斥信号 //读文件
printf(\Sleep(m_persist);
// 退出线程
printf(\//等待互斥信号,保证对readcount的访问、修改互斥 wait_for_mutex=WaitForSingleObject(h_Mutex,-1); //读者数目减少 readcount--; if(readcount==0) {
//如果所有读者读完,唤醒写者 LeaveCriticalSection(&RP_Write); }
ReleaseMutex(h_Mutex); //释放互斥信号 }
/////////////////////////////////////////////////////////////////////////// // 读者优先--写者线程 //p:写者线程信息
void RP_WriterThread(void* p) {
DWORD m_delay; // 延迟时间 DWORD m_persist; // 写文件持续时间 int m_serial; //线程序号 //从参数中获得信息
m_serial=((ThreadInfo*)(p))->serial;
m_delay=(DWORD)(((ThreadInfo*)(p))->delay*INTE_PER_SEC); m_persist=(DWORD)(((ThreadInfo*)(p)) ->persist*INTE_PER_SEC); Sleep(m_delay); //延迟等待
printf(\// 等待资源
EnterCriticalSection(&RP_Write); //写文件
printf(\Sleep(m_persist);
// 退出线程
printf(\//释放资源
LeaveCriticalSection(&RP_Write); }
/////////////////////////////////////////////////////////////////////////// // 读者优先处理函数 //file:文件名
void ReaderPriority(char* file)
共分享92篇相关文档