samedi 30 mai 2020

Why deadlock on std::this_thread::sleep_for on Visual Studio 2013

The code below can never print m4 (and of course no t2 and t3) on VS 2013. It behaves like a deadlock and I don't know the reason. Is there anything I missed?

#include <mutex>
#include <thread>
#include <chrono>

#include <stdio.h>

std::mutex m;

void work()
{
    printf("t1\n");

    m.lock();
    printf("t2\n");

    m.unlock();
    printf("t3\n");

    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    printf("m1\n");

    m.lock();
    printf("m2\n");

    std::thread *th = new std::thread(work);
    printf("m3\n");

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    printf("m4\n");

    m.unlock();
    printf("m5\n");

    while (true);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire