localtime与localtime_r
在寫代碼的時候,經常會用到讀取系統時間的函數。很多人都會調用localtime函數來將時間轉換本地時間,但是大家往往會忽略了一點,localtime函數不是線程安全的。如果在多線程里調用localtime函數,很可能會出現問題。
struct tm *localtime(const time_t *clock);
這個函數在返回的時候,返回的是一個指針,實際的內存是localtime內部通過static申請的靜態內存,所以通過localtime調用后的返回值不及時使用的話,很有可能被其他線程localtime調用所覆蓋掉
??? 多線程應用里面,應該用localtime_r函數替代localtime函數,因為localtime_r是線程安全的。
struct tm* localtime_r( const time_t* timer, struct tm* result );
轉載二:
上程序:
[c-sharp]?view plaincopy
最后出來的結果是:
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。
修改程序:
[c-sharp]?view plaincopy
最后出來的結果是:
10:29:06?
10:59:06
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生
總結
以上是生活随笔為你收集整理的localtime与localtime_r的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gcc __attribute__关键字
- 下一篇: 互斥锁属性PTHREAD_MUTEX_R