Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pthreads - 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
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...