user19631495
user19631495

Reputation:

Why does the first code NOT cause a dead-lock

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <thread>
std::mutex mtx;

void func2() {
    mtx.lock();
    std::cout << "here is 2" << std::endl;
    mtx.unlock();
}

void func1() {
    mtx.lock();
    std::cout << "here is 1" << std::endl;
    func2();
    mtx.unlock();
}

int main() {
    func1();
}

but if I modify the main func as follows, it cause dead lock

int main() {
    std::thread t1(func1);
    t1.join();
}

I complied both two by "g++ test.cpp -std=c++11 -lpthread"

Upvotes: 3

Views: 96

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Calling lock in the same thread twice (without unlocking the mutex) is undefined. From cppreference:

If lock is called by a thread that already owns the mutex, the behavior is undefined: for example, the program may deadlock.

It may deadlock. Or it may not. The behavior is undefined.

Note that std::recursive_mutex can be locked multiple times (though only up to some unspecified limit). However, code that needs a recursive mutex is more complicated. In your example it would be easier to remove the locking from func1, because it is only called when the mutex is already locked. In general it isn't that simple.

Upvotes: 6

Related Questions