c++multithreadingwinapicritical-section

The dining philosophers problem with critical section


I'm trying to solve the dining philosophers problem and each time it's printing that only 2 are eating. Each thread I created was a philosopher and each section was a fork and according to the algorithm, each time we send a philosopher we try to get his forks(for the first it's fork1 and fork2) and the forks are the critical sections. Any idea on How to fix this? Here's my code:

    #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

And that's the main:

    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
    }

Solution

  • probably two of the threads or more accessing to the same criticalSection and overlap eachother. try adding timer between each creation of a thread.

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