首页 > 解决方案 > 运行时错误多处理互斥体 - 进程同步

问题描述

我正在尝试解决经典的哲学家就餐问题。哲学家进餐问题指出,K 个哲学家围坐在一张圆桌旁,每对哲学家之间夹一根筷子。每个哲学家之间有一根筷子。哲学家如果能拿起旁边的两根筷子,就可以吃饭。一根筷子可以被它的任何一个相邻的追随者拿起,但不能同时被两个人拿起。我试图通过多处理来解决这个问题,这意味着每根筷子都是互斥体,每个哲学家都是一个过程。

HANDLE forks[NUMBER_OF_FORKS];

int main()
{
    STARTUPINFO si[NUMBER_OF_PHILOSOPHERS]; // NUMBER_OF_PHILOSOPHERS is 5
    PROCESS_INFORMATION pi[NUMBER_OF_PHILOSOPHERS]; // NUMBER_OF_PHILOSOPHERS is 5

    initForks(NUMBER_OF_PHILOSOPHERS); // The function initializing all the Mutexs

    std::string param;
    LPWSTR test;

    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        ZeroMemory(&si[i], sizeof(si[i]));
        si[i].cb = sizeof(si[i]);
        ZeroMemory(&pi[i], sizeof(pi[i]));
        
        // Converting the param to LPWSTR(The param represent the number of the philosopher).
        param = std::to_string(i);
        test = ConvertString(param);

        if (!CreateProcess(L"..\\Debug\\Philosopher.exe", test, NULL, NULL, FALSE, 0, NULL, NULL, &si[i], &pi[i]))
        {
            std::cout << GetLastError() << std::endl;;
        }
    }

    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        WaitForSingleObject(pi[i].hProcess, INFINITE);
    }
}

在第 17 行,当我使用 CreateProcess 函数时出现此错误: 显示错误

有人可以帮我发现问题吗?谢谢你们的帮助!

标签: multithreadingwinapiprocessmultiprocessingmutex

解决方案


从图片可以看出,

Expression : _p !- nullptr

你没有初始化test变量,试试这个,

LPWSTR test = new WCHAR[100];
memset(test, NULL, 200);
...

或者,

 std::string param;
 WCHAR test[100];
 param = std::to_string(i);
 mbstowcs(test, param.c_str(), param.size() + 1);  //Converts a multibyte character string from the array whose first element is pointed to by src to its wide character representation.
 

推荐阅读