TryEnterCriticalSection始终返回false

时间:2019-01-06 14:51:22

标签: c++ winapi

我正在尝试在WINAPI工具中实现就餐哲学家的问题。 我的目标是检查哲学家吃100万道菜最快的时间。 但是,我遇到一个问题,每次调用TryEnterCriticalSection都会返回false。

当我检查每个哲学家旁边的两把筷子是否可用于该功能时,就会发生这种情况。如果是的话,我们“吃”并提高计数器

我的主:

int nums[] = { 1, 2, 3, 4, 5 };
// initializes the critical sections
InitializeCriticalSection(&chopstick1);
InitializeCriticalSection(&chopstick2);
InitializeCriticalSection(&chopstick3);
InitializeCriticalSection(&chopstick4);
InitializeCriticalSection(&chopstick5);

// philosophers;
HANDLE WINAPI Phils[] = {
CreateThread(NULL, 0, threadFunc, &nums[0], 0, NULL),
CreateThread(NULL, 0, threadFunc, &nums[1], 0, NULL),
CreateThread(NULL, 0, threadFunc, &nums[2], 0, NULL),
CreateThread(NULL, 0, threadFunc, &nums[3], 0, NULL),
CreateThread(NULL, 0, threadFunc, &nums[4], 0, NULL)
};


WaitForMultipleObjects(5, Phils, TRUE, INFINITE);


return 0;

我的thread_func是:

    std::cout << "dev\n";
time_t before;
time_t after;
// before actions
time(&before);
int count = 0;
int* numP = (int*)lpParam;
int num = *numP;

if (num != 5 && num != 1)
{
    while (count < 1000000)
    {
        bool chop1 = TryEnterCriticalSection(&chopsticks[num - 2]);
        bool chop2 = TryEnterCriticalSection(&chopsticks[num]);
        if (chop1 == true && chop2 == true)
        {
            //enters
            EnterCriticalSection(&chopsticks[num - 2]);
            EnterCriticalSection(&chopsticks[num]);
            //eats
            count++;
            //leaves
            LeaveCriticalSection(&chopsticks[num - 2]);
            LeaveCriticalSection(&chopsticks[num]);
        }
    }
}
// if its the last one
if (num == 5)
{
    while (count < 1000000)
    {
        if (TryEnterCriticalSection(&chopsticks[num - 2]) && TryEnterCriticalSection(&chopsticks[0]))
        {
            //enters
            EnterCriticalSection(&chopsticks[num - 2]);
            EnterCriticalSection(&chopsticks[num]);
            //eats
            count++;
            //leaves
            LeaveCriticalSection(&chopsticks[num - 2]);
            LeaveCriticalSection(&chopsticks[num]);
        }
    }
}
// if its the first philosofer
if (num == 1)
{
    while (count < 1000000)
    {
        if (TryEnterCriticalSection(&chopsticks[4]) && TryEnterCriticalSection(&chopsticks[num - 1]))
        {
            //enters
            EnterCriticalSection(&chopsticks[num - 2]);
            EnterCriticalSection(&chopsticks[num]);
            //eats
            count++;
            //leaves
            LeaveCriticalSection(&chopsticks[num - 2]);
            LeaveCriticalSection(&chopsticks[num]);
        }
    }
}

time(&after);
std::cout << "Philosofer NO" << num << ": ate one million times for " << difftime(after, before) << " seconds" << std::endl;
return 0;

0 个答案:

没有答案