简体   繁体   中英

WaitForSingleObject Crash

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);
}

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 (ie joinable() == true), std::terminate() is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM