• 大小: 6KB
    文件类型: .rar
    金币: 1
    下载: 0 次
    发布日期: 2021-06-11
  • 语言: 其他
  • 标签:

资源简介

哲学家吃饭问题(vc代码) 哲学家吃饭问题(vc代码) 哲学家吃饭问题(vc代码) 哲学家吃饭问题(vc代码) 哲学家吃饭问题(vc代码)

资源截图

代码片段和文件信息

#include “windows.h“
#include “stdlib.h“
#include “stdio.h“
#include “iostream.h“
#include “process.h“

const int PHILOSOPHERS = 5;//哲学家人数
const int TIME_EATING = 50;//吃饭需要的时间 毫秒
HANDLE event[PHILOSOPHERS];//主线程同工作线程保持同步的句柄数组
HANDLE mutex[PHILOSOPHERS];//mutex数组,这里相当于公共资源筷子
CRITICAL_SECTION cs; //控制打印的临界区变量

UINT WINAPI ThreadFunc(void* arg)
{
    int num = (int)arg;
    
    DWORD ret = 0;
    while (1)
    {
        ret = WaitForMultipleobjects(2mutexTRUE1000);
        if (ret == WAIT_TIMEOUT)
        {
            Sleep(100);
            continue;
        }
        EnterCriticalSection(&cs);
cout << “philosopher “ << num << “ eatting“ << endl;
        LeaveCriticalSection(&cs);
        Sleep(TIME_EATING);
        break;
    }
    //设置时间为有信号
    SetEvent(event[num]);
    return 1;
}

int main(int argc char* argv[])
{
HANDLE hThread;
InitializeCriticalSection(&cs);
//循环建立线程
for (int i = 0; i < PHILOSOPHERS; i++)
{
mutex[i] = CreateMutex(NULL FALSE““);//INFINITE
event[i] = CreateEvent(NULL TRUE FALSE““);
hThread = (HANDLE)_beginthreadex(NULL0ThreadFunc(void*)i0NULL);
if (hThread == 0)
{
cout << “create thread “ << i << “failed with code: “<< GetLastError() << endl;
DeleteCriticalSection(&cs);
return -1;
}
CloseHandle(hThread);
}
//等待所有的哲学家吃饭结束
DWORD ret = WaitForMultipleobjects(PHILOSOPHERSeventTRUE INFINITE);
if (ret == WAIT_object_0)
{
cout << “all the philosophers had a dinner!“ << endl;
}
else
{
cout << “WaitForMultipleobjects failed with code: “ << GetLastError() << endl;
}
DeleteCriticalSection(&cs);
for (int j = 0; j < PHILOSOPHERS; j++)
{
CloseHandle(mutex[j]);
}
return 1;
}

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件       1827  2008-09-27 18:38  03\03.cpp

     文件       4273  2008-09-27 18:40  03\03.dsp

     文件        527  2008-09-27 17:30  03\03.dsw

     文件      41984  2008-09-28 09:34  03\03.ncb

     文件      54784  2008-09-28 09:34  03\03.opt

     文件        238  2008-09-28 09:16  03\03.plg

     目录          0  2008-09-28 09:35  03

----------- ---------  ---------- -----  ----

               103633                    7


评论

共有 条评论

相关资源