localtime 和 localtime_r


#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>

using namespace std;

int main(int argc, char *argv[])
{
    time_t tNow =time(NULL);
    time_t tEnd = tNow + 1800;
    //注意下面兩行的區別
    struct tm* ptm = localtime(&tNow);
    struct tm* ptmEnd = localtime(&tEnd);

    char szTmp[50] = {0};
    strftime(szTmp,50,"%H:%M:%S",ptm);
    char szEnd[50] = {0};
    strftime(szEnd,50,"%H:%M:%S",ptmEnd);
    
    printf("%s /n",szTmp);
    printf("%s /n",szEnd);
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

最后出來的結果是:

16:49:49
16:49:49

和最初想法不一致。

 

查閱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。

 

將location修改為location_r后,輸出結果:

16:22:02
16:52:02

 

localtime是直接返回strcut tm*指針(如果成功的話);這個指針是指向一個靜態變量的;因此,返回的指針所指向的靜態變量有可能被其他地方調用的localtime改掉,例如多線程使用的時候。

localtime_r則是由調用者在第二個參數傳入一個struct tm result指針,該函數會把結果填充到這個傳入的指針所指內存里面;成功的返回值指針也就是struct tm result。

其他的時間函數,如asctime,asctime_r;ctime,ctime_r;gmtime,gmtime_r都是類似的,所以,時間函數的 _r 版本都是線程安全的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM