【问题标题】:The dining philosophers problem with critical section临界区的哲学家进餐问题
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 你为什么使用std sleep和winapi CreateThread
  • 抱歉,不可以:您始终可以通过添加延迟来改变多线程程序的行为,从而防止出现各种不需要的状态,但这不是解决方案。如果你做事正确,你可以毫不拖延地这样做。
  • @ulr 这个建议的答案旁边有一个向下的箭头。它的工具提示显示:“这个答案没有用。”在您正确地确定这个建议的答案没有帮助之后,您为什么不单击箭头让其他读者知道?是不是令人恐惧的“这是一个新的贡献者,所以要温柔”的潮流再次适得其反?
  • @IInspectable,是的,有点:错误的答案是一回事,但被接受为正确答案的错误答案是另一回事。我认为这需要讨论一下。
  • @ulr 您是否将建议的答案评为有帮助可能取决于个人喜好。然而,这个提议的答案是非常有害的,因为它似乎解决了这个问题。这是必须投反对票。无需讨论。
猜你喜欢
  • 2019-02-07
  • 2010-10-26
  • 2016-03-04
  • 2014-04-11
  • 2020-05-05
  • 1970-01-01
  • 2010-10-11
  • 2015-10-14
  • 1970-01-01
相关资源
最近更新 更多