读写者问题

// 来自:windows 内核实验教程
// 机械工业出版社
// ISBN:7-111-10880-9/TP.2600
// 制作者:yuhejun@126.com
// For more information:www.surstar.com
// 2005.11.9
// beijing changping
// Debug Vision
// Description:这是一个关于操作系统内核实验的一段程序,读者和写者的问题的模拟实现.
// 开发环境:WINXP +VC6  Console Application
// 修改者:xiejh_buaa@163.com
// 修改时间: 2007-11-25
// 修改描述: 将代码中的Critical Section改为了信号量
#include "windows.h"
#include <conio.h>
#include <stdlib.h>
#include <fstream.h>
#include <io.h>
#include <string.h>
#include <stdio.h>
#include "winbase.h"

#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;

//
// 使用信号量代替临界区
HANDLE g_hSemophore1 = ::CreateSemaphore( NULL, 1, 1, NULL );
HANDLE g_hSemophore2 = ::CreateSemaphore( NULL, 1, 1, NULL );
HANDLE g_hSemophore3 = ::CreateSemaphore( NULL, 1, 1, NULL );

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,"mutex_for_readcount");
   
    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("Reader thread %d sents the reading require./n",m_serial);
    //等待互斥信号,保证对ReadCount 的访问,修改互斥
    wait_for_mutex=WaitForSingleObject(h_Mutex,-1);
    //读者数目增加
    readcount++;
    if(readcount==1)
    {
        //第一个读者,等待资源
        WaitForSingleObject( g_hSemophore1, -1 );
    }
    ReleaseMutex(h_Mutex);            //释放互斥信号
    //读文件
    printf("Reader thread %d begins to read file./n",m_serial);
    Sleep(m_persist);
    //退出线程
    printf("Reader thread %d finished reading file./n",m_serial);
    //等待互斥信号,保证对ReadCount的访问,修改互斥
    wait_for_mutex=WaitForSingleObject(h_Mutex,-1);
    //读者数目减少
    readcount--;
    if(readcount==0)
    {
        //如果所有的读者读完,唤醒写者
        ReleaseSemaphore( g_hSemophore1, 1, NULL );
    }
    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("Write thread %d sents the writing require./n",m_serial);
    //等待资源
    WaitForSingleObject( g_hSemophore1, -1 );
    //写文件
    printf("Writer thread %d begins to write to the file./n",m_serial);
    Sleep(m_persist);
    //退出线程
    printf("Write thread %d finished writing to the file./n",m_serial);
    //释放资源
    ReleaseSemaphore( g_hSemophore1, 1, NULL );
}

//
//读者优先处理函数
//file:文件名
void ReaderPriority(char *file)
{
    DWORD n_thread=0;           //线程数目
    DWORD thread_ID;            //线程ID
    DWORD wait_for_all;         //等待所有线程结束
   
    //互斥对象
    HANDLE h_Mutex;
    h_Mutex=CreateMutex(NULL,FALSE,"mutex_for_readcount");
    //线程对象的数组
    HANDLE h_Thread[MAX_THREAD_NUM];
    ThreadInfo thread_info[MAX_THREAD_NUM];
    readcount=0;               //初始化readcount
    ifstream inFile;
    inFile.open (file);
    printf("Reader Priority:/n/n");
    while(inFile)
    {
        //读入每一个读者,写者的信息
        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();
    }
    for(int i=0;i<(int)(n_thread-1);i++)
    {
        if(thread_info[i].entity==READER||thread_info[i].entity =='r')
        {
            //创建读者进程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(RP_ReaderThread),&thread_info[i],0,&thread_ID);
        }
        else
        {
            //创建写线程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(RP_WriterThread),&thread_info[i],0,&thread_ID);
        }
    }
    //等待所有的线程结束
    wait_for_all=WaitForMultipleObjects(n_thread,h_Thread,TRUE,-1);
    printf("All reader and writer have finished operating./n");
}


//写者优先---读者线程
//P:读者线程信息
void WP_ReaderThread(void *p)
{
    //互斥变量
    HANDLE h_Mutex1;
    h_Mutex1=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex1");
    HANDLE h_Mutex2;
    h_Mutex2=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex2");
    DWORD wait_for_mutex1;            //等待互斥变量所有权
    DWORD wait_for_mutex2;
    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("Reader thread %d sents the reading require./n",m_serial);
    wait_for_mutex1=WaitForSingleObject(h_Mutex1,-1);
    //读者进去临界区
    WaitForSingleObject( g_hSemophore3, -1 );
    //阻塞互斥对象Mutex2,保证对readCount的访问和修改互斥
    wait_for_mutex2=WaitForSingleObject(h_Mutex2,-1);
    //修改读者的数目
    readcount++;
    if(readcount==1)
    {
        // 如果是第1个读者,等待写者写完
        WaitForSingleObject( g_hSemophore2, -1 );
    }
    ReleaseMutex(h_Mutex2);// 释放互斥信号 Mutex2
    //让其他读者进去临界区
    ReleaseSemaphore( g_hSemophore3, 1, NULL );
    ReleaseMutex(h_Mutex1);
    //读文件
    printf("Reader thread %d begins to read file./n",m_serial);
    Sleep(m_persist);
    //退出线程
    printf("Reader thread %d finished reading  file./n",m_serial);
    //阻塞互斥对象Mutex2,保证对readcount的访问,修改互斥
    wait_for_mutex2=WaitForSingleObject(h_Mutex2,-1);
    readcount--;
    if(readcount==0)
    {
        //最后一个读者,唤醒写者
        ReleaseSemaphore( g_hSemophore2, 1, NULL );
    }
    ReleaseMutex(h_Mutex2);  //释放互斥信号
}

///
//写者优先---写者线程
//P:写者线程信息
void WP_WriterThread(void *p)
{
    DWORD wait_for_mutex3;            //互斥变量
    DWORD m_delay;                   //延迟时间
    DWORD m_persist;                 //读文件持续时间
    int m_serial;                    //线程序号
    HANDLE h_Mutex3;
    h_Mutex3=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex3");
    //从参数中获得信息
    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("Writer thread %d sents the writing require./n",m_serial);
    wait_for_mutex3=WaitForSingleObject(h_Mutex3,-1);
    writecount++;               //修改写者数目
    if(writecount==1)
    {
        WaitForSingleObject( g_hSemophore3, -1 );
    }
    ReleaseMutex(h_Mutex3);
    WaitForSingleObject( g_hSemophore2, -1 );
    printf("Writer thread %d begins to write to the file./n",m_serial);
    Sleep(m_persist);
    printf("Writer thread %d finished writing to the file./n",m_serial);
    ReleaseSemaphore( g_hSemophore2, 1, NULL );
    wait_for_mutex3=WaitForSingleObject(h_Mutex3,-1);
    writecount--;
    if(writecount==0)
    {
        ReleaseSemaphore( g_hSemophore3, 1, NULL );
    }
    ReleaseMutex(h_Mutex3);
}

/
//写者优先处理函数
// file:文件名
void WriterPriority(char * file)
{
    DWORD n_thread=0;
    DWORD thread_ID;
    DWORD wait_for_all;
    HANDLE h_Mutex1;
    h_Mutex1=CreateMutex(NULL,FALSE,"mutex1");
    HANDLE h_Mutex2;
    h_Mutex2=CreateMutex(NULL,FALSE,"mutex2");
    HANDLE h_Mutex3;
    h_Mutex3=CreateMutex(NULL,FALSE,"mutex3");
    HANDLE h_Thread[MAX_THREAD_NUM];
    ThreadInfo thread_info[MAX_THREAD_NUM];
    readcount=0;
    writecount=0;
    ifstream inFile;
    inFile.open (file);
    printf("Writer priority:/n/n");
    while(inFile)
    {
        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();
    }
    for(int i=0;i<(int)(n_thread-1);i++)
    {
        if(thread_info[i].entity==READER||thread_info[i].entity =='r')
        {
            //创建读者进程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(WP_ReaderThread),&thread_info[i],0,&thread_ID);
        }
        else
        {
            //创建写线程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(WP_WriterThread),&thread_info[i],0,&thread_ID);
        }
    }
    //等待所有的线程结束
    wait_for_all=WaitForMultipleObjects(n_thread,h_Thread,TRUE,-1);
    printf("All reader and writer have finished operating./n");
}

/
//主函数
int main(int argc,char *argv[])
{
    char ch;
    while(true)
    {
        printf("*************************************/n");
        printf("   1.Reader Priority/n");
        printf("   2.Writer Priority/n");
        printf("   3.Exit to Windows/n");
        printf("*************************************/n");
        printf("Enter your choice(1,2,3): ");
        do{
            ch=(char)_getch();
        }while(ch!='1'&&ch!='2'&&ch!='3');
        system("cls");
        if(ch=='3')
            return 0;
        else if(ch=='1')
            ReaderPriority("thread.dat");
        else
            WriterPriority("thread.dat");
        printf("/nPress Any Key to Coutinue:");
        _getch();
        system("cls");
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Windows2000环境下,创建一个控制台进程,此进程包含n个线程。用这n个线程来表示n个读者或写者。每个线程按相应测试数据文件(后面有介绍)的要求进行读写操作。用信号量机制分别实现读者优先和写者优先的读者-写者问题。 读者-写者问题读写操作限制(包括读者优先和写者优先): 1)写-写互斥,即不能有两个写者同时进行写操作。 2)读-写互斥,即不能同时有一个线程在读,而另一个线程在写。, 3)读-读允许,即可以有一个或多个读者在读。 读者优先的附加限制:如果一个读者申请进行读操作时已有另一个读者正在进行读操作,则该读者可直接开始读操作。 写者优先的附加限制:如果一个读者申请进行读操作时已有另一写者在等待访问共享资源,则该读者必须等到没有写者处于等待状态后才能开始读操作。 运行结果显示要求:要求在每个线程创建、发出读写操作申请、开始读写操作和结束读写操作时分别显示一行提示信息,以确定所有处理都遵守相应的读写操作限制。 2测试数据文件格式 测试数据文件包括n行测试数据,分别描述创建的n个线程是读者还是写者,以及读写操作的开始时间和持续时间。每行测试数据包括四个字段,各个字段间用空格分隔。第一字段为一个正整数,表示线程序号。第二字段表示相应线程角色,R表示读者,w表示写者。第三字段为一个正数,表示读写操作的开始时间:线程创建后,延迟相应时间(单位为秒)后发出对共享资源的读写申请。第四字段为一个正数,表示读写操作的持续时间。当线程读写申请成功后,开始对共 享资源的读写操作,该操作持续相应时间后结束,并释放共享资源。 下面是一个测试数据文件的例子: 2 W 4 5 3 R 5 2 4 R 6 5 5 W 5.1 3
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值