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
mainmethod exits. The destructors on thethreadobjects are being called without the thread exiting. You need to calljoinin order to have your main method wait. Try:According to std::thread destructor docs: