localtime 和 localtime_r

本文通过实例代码分析了C++中localtime和localtime_r的区别,指出localtime不是线程安全的,而localtime_r是可重入的,适合多线程环境。并展示了如何使用localtime_r修正程序以避免数据重写问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上程序:

最后出来的结果是:

21:18:39

21:18:39

和最初想法不一致。

 

查阅localtime的文档,发现这段话:

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

也就是说每次只能同时使用localtime()函数一次,要不就会被重写!

The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

因此localtime()不是可重入的。同时libc里提供了一个可重入版的函数localtime_r();

Unlike localtime(), the reentrant version is not required to set tzname。

修改程序:

最后出来的结果是:

10:29:06
10:59:06

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值