Ben
Ben

Reputation: 4676

EnterCriticalSection crashes with more than 64 threads

Is there a thread limit EnterCriticalSection() can cope with? The following code works fine with 64 threads, but it crashes when using 65 or more:

CRITICAL_SECTION TestCritSection;

unsigned int threadId;

int getThreadId()
{
    int tid = -1;

    EnterCriticalSection(&TestCritSection);

    tid= threadId;
    threadId++;

    LeaveCriticalSection(&TestCritSection);

    return tid;
}

void parallelTest()
{
    int tid = getThreadId();
    cout << "Thread " << tid << " executed" << endl;
}


void
multiThreadTest()
{
    unsigned int numThreads = 64; // fine, but program crashes when numThreads is set to 65 or more
    HANDLE *threads = new HANDLE[numThreads];
    DWORD ThreadID;
    threadId = 1;

    if (!InitializeCriticalSectionAndSpinCount(&TestCritSection, 0x00000400)) return;

    for (int i=0; i<numThreads; ++i)
    {
        threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) parallelTest, (LPVOID) NULL, 0, &ThreadID);
    }

    WaitForMultipleObjects(numThreads, threads, TRUE, INFINITE);

    DeleteCriticalSection(&TestCritSection);

    for (int i=0; i<numThreads; ++i)
    {
        CloseHandle(threads[i]);
    }

    delete [] threads;
}

I guess CRITICAL_SECTION is internally using a semaphore with a max count of 64. Can I somehow change that?

Upvotes: 0

Views: 2009

Answers (1)

Ben
Ben

Reputation: 4676

As nobody wants to answer my question, I will do it myself based on HansPassant's comment to my question.

He pointed out that the problem is WaitForMultipleObjects(), which takes a parameter

nCount [in]

The number of object handles in the array pointed to by lpHandles.

The maximum number of object handles is MAXIMUM_WAIT_OBJECTS. This parameter cannot be zero.

(from msdn)

MAXIMUM_WAIT_OBJECTS is defined as 64, more informations in this thread.

This means: yes, there is a hard-coded limit on the amount of threads, but the restriction is not on EnterCriticalSection but on WaitForMultipleObjects, which returns an error code I should have checked.

Here is more information on how to get more than 64 threads working in parallel.

Upvotes: 1

Related Questions