Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 thread/mutex implementation in VS2012 - assertion fired

I want to move my code from boost- to std-threads. While I thought it should be quite straight forward I'm running into weird problems. The code below is a minimal example which fires an assertion "f:\dd\vctools\crt_bld\self_x86\crt\src\thr\mutex.c(131):unlock of unowned mutex" with VS2012. Searching for this brings up older bug reports which (i think) should be already fixed.

int result = 0;
std::mutex m;
m.lock();
std::thread t1([&](){
    result = 42;
    m.unlock();
});
m.lock();
std::cout << result << std::endl;
t1.join();

Can someone explain to me why this doesn't work?

Thanks

like image 389
Daniel Avatar asked Dec 21 '22 11:12

Daniel


1 Answers

m.unlock() requires that the calling thread owns the mutex. Your code does not meet that requirement (as the unlock()ing thread never calls m.lock()) and so the program's behavior is undefined.

like image 95
bames53 Avatar answered Dec 24 '22 00:12

bames53