Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c++ - Why does libc++ allow recursive locking of std::mutex?

std::mutex is nonrecursive, and violation of that is UB. So anything is possible in theory(including works as std::recursive_mutex)), but libc++ seems to work fine , this program outputs

bye

#include <iostream>
#include <mutex>

std::mutex m;
int main() {
    std::scoped_lock l1(m);
    std::scoped_lock l2(m);
    std::cout << "bye" << std::endl;
}

Is this intentional design decision in libc++ or just some accident(for example they could use same logic for mutex and recursive_mutex)?

libstdc++ hangs.

note: I am aware of that people should not rely on UB, so this is not about best practices, I am just curious about obscure implementation details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I get the opposite results: libc++ hangs and libstdc++ doesn't

The reason is that if the file is not compiled with -pthread, threading support is disabled and std::mutex::lock/unlock become noops. Adding -pthread makes both of them deadlock as expected.

libc++ is built with threading support by default and doesn't require the -pthread flag, so it std::mutex::lock does actually acquire a lock, creating the deadlock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...