电话亭问题

电话亭问题_第1张图片

电话亭问题_第2张图片

电话亭问题_第3张图片

电话亭问题_第4张图片

 

电话亭问题_第5张图片

 

 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
using namespace std;

#define BOY 'B'  //读者
#define GIRL 'G'  //写者
#define DELAY_TIME 700  //最基本的延迟时间,其他都为他的倍数
#define MAX_THREAD_NUM 64 //最大线程数
int boys_waiting = 0;
int girls_waiting = 0;
int usingnum = 0;
//临界区
CRITICAL_SECTION S_girls;
CRITICAL_SECTION S_boys;
//线程结构体
struct Thread{
    int serial;  //线程序号
    char entity;   //判断是男生还是女生
    double delay;   //线程延迟
    double persist; //线程写操作持续时间
};
//写者优先 读者进程
void GP_BoyThread(void *p)
{
    //互斥变量
    HANDLE h_Mutex;
    h_Mutex = OpenMutex(MUTEX_ALL_ACCESS,false,"mutex1");
    DWORD m_delay = (DWORD)(((Thread*)(p))->delay*DELAY_TIME);
    DWORD m_persist = (DWORD)(((Thread*)(p))->persist*DELAY_TIME);
    int m_serial = ((Thread*)(p))->serial;
    Sleep(m_delay);//延迟等待
    cout<<"男生线程 "< 0){
        girls_waiting--;
        LeaveCriticalSection(&S_girls);//V临界区
    }
    else if(boys_waiting >0){
        boys_waiting--;
        LeaveCriticalSection(&S_boys);
    }
    else usingnum = 0;
    ReleaseMutex(h_Mutex);
}
//写者优先 写者进程
void GP_GirlThread(void *p){
   //互斥变量
    HANDLE h_Mutex;
    h_Mutex = OpenMutex(MUTEX_ALL_ACCESS,false,"mutex1");
    DWORD m_delay = (DWORD)(((Thread*)(p))->delay*DELAY_TIME);
    DWORD m_persist = (DWORD)(((Thread*)(p))->persist*DELAY_TIME);
    int m_serial = ((Thread*)(p))->serial;
    Sleep(m_delay);//延迟等待
    cout<<"女生线程 "< 0){
        girls_waiting--;
        LeaveCriticalSection(&S_girls);
    }
    else if(boys_waiting >0){
        boys_waiting--;
        LeaveCriticalSection(&S_boys);
    }
    else usingnum = 0;
    ReleaseMutex(h_Mutex);
}
void WriterPriority(char *file){
    DWORD n_thread=0; //线程数目
    DWORD thread_ID;//线程ID

    //创建线程数组
    HANDLE h_Thread[MAX_THREAD_NUM];
    Thread threads[MAX_THREAD_NUM];
    //初始化计数器和临界区
    boys_waiting  = 0;
    girls_waiting = 0;
    InitializeCriticalSection(&S_boys);
    InitializeCriticalSection(&S_girls);
    //打开文件
    ifstream inFile;
    inFile.open(file);
    cout<<"程序开始:"<>threads[n_thread].serial;
        inFile>>threads[n_thread].entity;
        inFile>>threads[n_thread].delay;
        inFile>>threads[n_thread++].persist;
        inFile.get();
    }
    for(int i=0;i<(int)(n_thread);i++){
        if(threads[i].entity==BOY||threads[i].entity=='b')
        {
            //创建男孩线程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(GP_BoyThread),&threads[i],0,&thread_ID);
        }
        else
            //创建女孩线程
            h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(GP_GirlThread),&threads[i],0,&thread_ID);
    }
     WaitForMultipleObjects(n_thread,h_Thread,true,-1);
    cout<<"所有的男孩和女孩都进入过电话亭。"<>num;
        if(num<1||num>2)
        {
            cout<<"输入无效,请重新输入"<

 

你可能感兴趣的:(操作系统)