Why is gcc referenced without the lpthread flag?

I worked on a hobby project where the mutexes behaved mysteriously. I screwed it into this test case, which obviously should have come to a standstill.

#include <pthread.h> #include <stdio.h> int main() { pthread_mutex_t test; pthread_mutex_init(&test, NULL); pthread_mutex_lock(&test); pthread_mutex_lock(&test); printf("Took lock twice\n"); return 0; } 

However, when I compile without the -lpthread flag, the program not only compiles and binds, but also works without deadlock. Why?

 gcc pthread_break.c -o pthread_test ./pthread_test Took lock twice 

Compiling with the -lpthread flag gives the expected result:

 gcc pthread_break.c -o pthread_test -lpthread ./pthread_test <- deadlocked here 

I am running GCC version 7.2.0.

+5
source share
1 answer

There seems to be no information in the information - but it seems that there are two options:

First, the mutex is initiated using PTHREAD_MUTEX_RECURSIVE , which will block the mutex duels - the number of links is checked, and the mutex is released only when the number of links is 0. This means that you can block the same mutex several times in the same stream, but for that To release it, you must provide the same number of locks.

Secondly, gcc in this version only implements stubs for pthread functions, which means that if you do not add the library binding directive -lpthread , the lock functions will not be implemented. This is confirmed by the fact that after adding the option a deadlock appears.

I will try to go through the GCC source to make sure that this is really the result of the second option - add an update.

NOTE. It is always recommended that you link libraries as it allows you to control the result. Failure to support GCC internally can lead to unexpected behavior, as shown above.

+1
source

Source: https://habr.com/ru/post/1273906/


All Articles