问题
Why is it that creating a std::mutex deadlock will not actually cause a deadlock unless the program is linked to pthreads?
The following will deadlock when linked with pthreads library and will not deadlock if pthreads is not linked in. Tested on gcc and clang.
// clang++ main.cpp -std=c++14 -lpthread
#include <mutex>
int main() {
std::mutex mtx;
mtx.lock();
mtx.lock();
return 0;
}
I understand that without a thread library you don't actually need mutex functionality, but is the compiler aware of the libraries that are linked in? And can it optimized based on that?
回答1:
The following will deadlock when linked with pthreads library and will not deadlock if pthreads is not linked in.
That's because the default implementation of std::mutex::lock
does nothing.
is the compiler aware of the libraries that are linked in?
No: the compiler simply calls std::mutex::lock
and passes it the address of mtx
. It's the implementation of that function that behaves differently.
Update:
To clarify, the implementation is able to change itself depending on if a library has been linked in? Through a macro?
By the time the compiler is done compiling, macro preprocessing is also done and can not have any further effect.
Perhaps it's best to demonstrate. Suppose you have:
int main() { return foo(); }
Can you tell what the result of execution of above program is? No, you can't, because you don't know what foo
does.
Suppose now that I compile the following:
// foo.c
int foo() { return 0; }
gcc -c foo.c && ar ruv libfoo.a foo.o
gcc main.o -L. -lfoo
Now you can tell that the program will exit with 0
return code.
Now suppose that I also compile the following:
// bar.c
int foo() { abort(); }
gcc -c bar.c && ar ruv libbar.a bar.o
Finally, I link the same unmodified main.o
like so:
gcc main.o -L. -lbar -lfoo
Can you tell what the resulting program will do?
You can: it will die with SIGABRT
and produce a core dump.
Notice that main.o
did not change, only the libraries that main.o
is being linked against have changed.
This is exactly the same mechanism that causes your original program to behave differently depending on whether or not it is linked against libpthread
.
来源:https://stackoverflow.com/questions/43826397/no-deadlock-unless-linked-to-pthreads