-pthread 和 -lpthread 的区别

pthread和-lpthread在编译链接时有所不同。-pthread不仅链接pthread库,还定义了_REENTRANT宏,确保线程安全。对于现代编译器,两者差异不大,但在旧系统或不同Unix变种中,-pthread更具可移植性。_REENTRANT宏用于启用多线程支持,但现在主要是兼容性作用。建议在多线程编程中使用-pthread以保证代码的兼容性和安全性。

-pthread 和-lpthread区别就是少了个l, 教材都是在编译的链接的时候要求加下-lpthread 解决链接的问题

gcc的官方说明是

-pthread

Define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. This option is supported on GNU/Linux

targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets.


就是相对于-lpthread 多定义了一些编译宏,

使用下面的方法 导出下默认的编译宏,对比了下, 发现多了个_REENTRANT

ubuntu@ubuntu-nvidia:~$ gcc -dM -E -pthread - </dev/null > pthread
ubuntu@ubuntu-nvidia:~$ gcc -dM -E - </dev/null > nopthread
ubuntu@ubuntu-nvidia:~$ diff pthread nopthread
105d104
< #define _REENTRANT 1


这个宏的作用如下

Macro: _REENTRANT

These macros are obsolete. They have the same effect as defining _POSIX_C_SOURCE with the value 199506L.

Some very old C libraries required one of these macros to be defined for basic functionality (e.g. getchar) to be thread-safe.


这个宏可以保证一些函数是线程安全的,但是现在相当于是一个兼容性的作用,在 1995 edition of the POSIX.1c standard (IEEE Standard 1003.1c-1995) 以前你可能需要加下。

To compile a single-threaded application, define neither the -D_REENTRANT nor the -D_POSIX_C_SOURCE flag. When these flags are not present, all the old definitions for errno, stdio, and so on, remain in effect.
 

有些年头了,像errno现在早就是函数了

总结:

对现在版本的编译器和c库没啥区别,对老古董,多线程的时候你最好使用-pthread, 他可以让你的代码更安全。

  1. 为了可移植性:在Linux中,pthread是作为一个单独的库存在的(libpthread.so),但是在其他Unix变种中却不一定,比如在FreeBSD中是没有单独的pthread库的,因此在FreeBSD中不能使用-lpthread来链接pthread,而使用-pthread则不会存在这个问题,因为FreeBSD的编译器能正确将-pthread展开为该系统下的依赖参数。同样道理,其他不同的变种也会有这样那样的区别,如果使用-lpthread,则可能在移植到其他Unix变种中时会出现问题,为了保持较高的可移植性,我们最好还是使用-pthread(尽管这种做法未被接纳成为C标准,但已基本是事实标准)。
  2. 添加额外的标志:在多数系统中,-pthread会被展开为“-D_REENTRANT -lpthread”,即是除了链接pthread库外,还先定义了宏_REENTRANT。定义这个宏的目的,是为了打开系统头文件中的各种多线程支持分支。比如,我们常常使用的错误码标志errno,如果没有定义_REENTRANT,则实现为一个全局变量;若是定义了_REENTRANT,则会实现为每线程独有,从而避免线程竞争错误。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值