WaitForSingleObject Crash

2.4k views Asked by At

I am trying to protect a section of code through the use of a mutex. Due to the code crashing I've created a simple bit of test code below which does the same. The crash is not necessarily on the same line of code each time but is always around the "WaitForSingleObject" or "Sleep" calls.

Any assistance would be appreciated.

#include <thread>
#include <windows.h>
#include <process.h>

static HANDLE myMutex;

//The function we want to make the thread run.
void task1()
{

    WaitForSingleObject(myMutex, INFINITE);

    for (int i = 0; i < 20; i++)
    {
        Sleep(500);
    }

    ReleaseMutex(myMutex);
}

void task2()
{

    Sleep(10);
    WaitForSingleObject(myMutex, INFINITE);

    for (int i = 0; i < 20; i++)
    {
        Sleep(10);
    }

    ReleaseMutex(myMutex);
}

int main(int argc, char **argv)
{

    myMutex = CreateMutex(0, FALSE, 0);

    std::thread t1(task1);

    std::thread t2(task2);
}
1

There are 1 answers

0
Steve On

The problem is that you're not waiting for the threads to exit before your main method exits. The destructors on the thread objects are being called without the thread exiting. You need to call join in order to have your main method wait. Try:

int main(int argc, char **argv)
{

    myMutex = CreateMutex(0, FALSE, 0);

    std::thread t1(task1);

    std::thread t2(task2);
    if(t1.joinable())
        t1.join();

    if(t2.joinable())
        t2.join();

}

According to std::thread destructor docs:

Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.