【发布时间】:2021-04-22 01:40:26
【问题描述】:
我正在尝试解决哲学家进餐问题,每次打印时只有 2 个在进餐。 我创建的每个线程都是一个哲学家,每个部分都是一个叉子,根据算法,每次我们发送一个哲学家时,我们都会尝试获取他的叉子(首先是叉子 1 和叉子 2),叉子是关键部分。关于如何解决这个问题的任何想法? 这是我的代码:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <tchar.h>
#include <iostream>
#include <chrono>//To check runtime(it was also asked but I know how to do this)
#include <thread>
using namespace std;
CRITICAL_SECTION ghCARITICALSection1;
CRITICAL_SECTION ghCARITICALSection2;
//Same for the rest
DWORD WINAPI func(int* phiphilosopher)
{
if (1 == *phiphilosopher)
{
if (TryEnterCriticalSection(&ghCARITICALSection1)) {
if (TryEnterCriticalSection(&ghCARITICALSection2)) {
cout << "1 is eating..."<< endl;
for (int i = 0; i < 1000000; i++)
{
i = i;
}
LeaveCriticalSection(&ghCARITICALSection2);
}
LeaveCriticalSection(&ghCARITICALSection1);
}
}
//Same for the rest but with all the numbers increased and on the 5th we check 5 and 1
这是主要的:
int main()
{
int philosopher1 = 1;
int* philosopher1ptr = &philosopher1;
//Same for the rest
InitializeCriticalSection(&ghCARITICALSection1);
InitializeCriticalSection(&ghCARITICALSection2);
//Same for the rest
HANDLE WINAPI th1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, philosopher1ptr, 0, NULL);
//Same for the rest
WaitForSingleObject(th1, INFINITE);
//Same for the rest
}
【问题讨论】:
-
什么是哲学家进餐问题?
-
查看这里:link
-
你的问题描述直接属于问题。
-
我不认为我完全明白你的意思。
-
好吧,如果你和 5 个哲学家一起尝试这个问题,那么最多 2 个应该在吃饭。
标签: c++ multithreading winapi critical-section