I recently stumbled upon what I thought was quite a weird behavior of the pthreads library (or at least its implementation in Linux Mint 16, Ubuntu EGLIBC 2.17-93ubuntu4, NPTL 2.17, gcc Ubuntu/Linaro 4.8.1-10ubuntu9 ).
When compiling a pthreads program, I accidentally forgot to link it with the pthreads library (i.e., I forgot to add the -lpthread flag to the gcc command line). I did, however, compile the program with all warnings enabled (-Wall) and received absolutely no warnings or errors. When I ran the program, thought, it appeared as if the locks were simply not working. It took me a little while to figure out, but eventually I found out that despite all the calls to pthread_mutex_lock were returning 0 (success), the locks were not being set (i.e., for example, two sequential calls to pthread_mutex_lock on the same lock would not suspend execution).
Here's a proof of concept code that I used to test and reproduce the behavior:
int main( int argc, char **argv ) {
pthread_mutex_t mutex;
pthread_mutex_init( &mutex, NULL );
pthread_mutex_lock( &mutex );
pthread_mutex_lock( &mutex );
pthread_mutex_unlock( &mutex );
return 0;
}
If I compile it without the -lpthread flag, I get no errors or warnings and when I run it, it simple runs normally and finishes executing.
me@mybox /tmp $ gcc -Wall mutex.c -o mutex
me@mybox /tmp $ ./mutex
me@mybox /tmp $
If I compile it with the -lpthread flag, I also do not get any errors or warnings, but when I run it, it simply hangs (on the second call to pthread_mutex_lock) - which should be the expected behavior.
me@mybox /tmp $ gcc -Wall mutex.c -o mutex -lpthread
me@mybox /tmp $ ./mutex
^C
me@mybox /tmp $
Can anybody explain why, when the -lpthread flag is omitted (and thus the program is not linked to the pthreads library), the compiler shows no error or warnings, nor does the program during its execution, but pthread_mutex_lock simply returns 0 and does not hold the lock?
Thank you in advance for any clues you can provide.