链接-lpthread会改变应用程序的行为吗? (Linux,Glibc) [英] Does linking an `-lpthread` changes application behaviour? (Linux, Glibc)

查看:57
本文介绍了链接-lpthread会改变应用程序的行为吗? (Linux,Glibc)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:如果我们有一个不使用线程的应用程序,我们可以通过两种方式链接它:

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

1)照常链接,没有-lpthread-ldl

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

2)将两个库添加到链接:libpthread和libdl.

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

例如

$ 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

版本a和版本a1之间会有多少区别?在应用程序本身和int glibc内部将以什么不同的方式工作? pthread的链接会将内部的内容从不安全线程更改为线程安全算法吗?

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?

例如

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

在a1跟踪中,将加载两个附加的库,调用更多的mprotect,并添加以下部分:

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

推荐答案

glibc本身包含许多pthread函数的存根代码.这些glibc pthread函数不执行任何操作.但是,当程序与libpthread链接时,这些存根将被真正的pthread锁定功能取代.

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.

这旨在用于需要线程安全但不使用线程本身的库中.这些库可以使用pthread锁,但是只有在加载了链接到libpthread的程序或库之后,这些锁才会真正发生.

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.

这篇关于链接-lpthread会改变应用程序的行为吗? (Linux,Glibc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆