带临界区的哲学家就餐问题

The dining philosophers problem with critical section

我正在尝试解决哲学家就餐问题,但每次它都打印出只有 2 个在吃饭。 我创建的每个线程都是一个哲学家,每个部分都是一个叉子,根据算法,每次我们发送一个哲学家时,我们都会尝试获取他的叉子(首先是 fork1 和 fork2),叉子是关键部分。关于如何解决这个问题的任何想法? 这是我的代码:

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

可能有两个或更多线程访问同一个 criticalSection 并相互重叠。 尝试在每次创建线程之间添加计时器。

HANDLE WINAPI th1 = CreateThread(...);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
HANDLE WINAPI th2 = CreateThread(...);