c++multithreadingdining-philosopher

Dining philosophers problem - only 2 thread worked


I am trying to solve the dining philosophers problem.

In my case, every philosopher should eat 1,000,000 times. The problem is that it seems like only "1" and is "3" finished eating. I am using threads with critical section lock, here is my code:

CRITICAL_SECTION ghCARITICALSection1;
CRITICAL_SECTION ghCARITICALSection2;
CRITICAL_SECTION ghCARITICALSection3;
CRITICAL_SECTION ghCARITICALSection4;
CRITICAL_SECTION ghCARITICALSection5;
DWORD WINAPI func(int* phiphilosopher)
{
    if (1 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection1) && TryEnterCriticalSection(&ghCARITICALSection2))
    {
        std::cout << "1 is eating...\n";
        for (int i = 0; i < 1000000; i++)
        {
            i = i;
        }
        LeaveCriticalSection(&ghCARITICALSection1);
        LeaveCriticalSection(&ghCARITICALSection2);
    }
    if (2 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection2) && TryEnterCriticalSection(&ghCARITICALSection3))
    {
        std::cout << "2 is eating...\n";
        for (int i = 0; i < 1000000; i++)
        {
        }
        LeaveCriticalSection(&ghCARITICALSection2);
        LeaveCriticalSection(&ghCARITICALSection3);
    }
    if (3 == *phiphilosopher && TryEnterCriticalSection(&ghCARITICALSection3) && TryEnterCriticalSection(&ghCARITICALSection4))
    {
        std::cout << "3 is eating...\n";
        for (int i = 0; i < 1000000; i++)
        {
        }
        LeaveCriticalSection(&ghCARITICALSection3);
        LeaveCriticalSection(&ghCARITICALSection4);
    }
    //...also for 4,5
    return 0;
}
    int philosopher1 = 1;
    int* philosopher1ptr = &philosopher1;
    int philosopher2 = 2;
    int* philosopher2ptr = &philosopher2;
    //...Also for philosopher 3,4,5

    InitializeCriticalSection(&ghCARITICALSection1);
    InitializeCriticalSection(&ghCARITICALSection2);
//...aslo for ghCARITICALSection 3,4,5

    HANDLE WINAPI th1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, philosopher1ptr, 0, NULL);
    HANDLE WINAPI th2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, philosopher2ptr, 0, NULL);
////...aslo for th3,4,5
    WaitForSingleObject(th1, INFINITE);
    WaitForSingleObject(th2, INFINITE);
    //...also for th3,4,5

Solution

  • Think about the logic here

        if (TryEnterCriticalSection(&a) && TryEnterCriticalSection(&b)) {
            // . . .
            LeaveCriticalSection(&a);
            LeaveCriticalSection(&b);
        }
    

    What happens if TryEnterCriticalSection(&a) succeeds and TryEnterCriticalSection(&b) fails; the CS a remains in entered state forever.

    It should look something like

        if (TryEnterCriticalSection(&a)) {
            if (TryEnterCriticalSection(&b)) {
                // . . .
                LeaveCriticalSection(&b);
            }
            LeaveCriticalSection(&a);
        }