Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does linking an `-lpthread` changes application behaviour? (Linux, Glibc)

I have a question: if we have an application, which uses no threads, we can link it in two ways:

1) Link as usual, without -lpthread and -ldl

2) Add to the link two libraries: libpthread and libdl.

E.g.

$ cat a.c
int main(){printf("Hehe");}
$ gcc a.c -w -o a
$ gcc a.c -w -o a1 -ldl -lpthread

By default, both libs are dynamically linked:

$ ldd a
    linux-gate.so.1
    libc.so.6
    /lib/ld-linux.so.2
$ ldd a1
    linux-gate.so.1
    libdl.so.2
    libpthread.so.0
    libc.so.6
    /lib/ld-linux.so.2

How much difference will be there between version a and version a1 ? What will be working in different way inside application itself and int glibc ? Will linking of pthreads change something inside from thread-unsafe to thread-safe algorithm?

E.g.

$ strace ./a 2>&1 |wc -l
     73
$ strace ./a1 2>&1 |wc -l
    103

In a1 trace, two additional libs are loaded, some more mprotects are called, and added section of:

 set_tid_address; set_robust_list; rt_sigaction x 2; rt_sigprocmask; getrlimit; uname
like image 492
osgx Avatar asked Jun 07 '11 13:06

osgx


1 Answers

glibc itself contains stub code for many pthread functions. These glibc pthread functions do nothing. However, when the program is linked with libpthread then those stubs are replaced with the real pthread locking functions.

This is intended for use in libraries that need to be thread safe but do not use threads themselves. These libraries can use pthread locks, but those locks will not actually happen until a program or library that links to libpthread is loaded.

like image 197
Zan Lynx Avatar answered Oct 16 '22 22:10

Zan Lynx