zoukankan      html  css  js  c++  java
  • localtime多线下不安全,localtime_r线程安全

    引用:http://blog.csdn.net/maocl1983/article/details/6221810

    localtime的英文解析:

    his 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();

    #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;
    }

    最后出来的结果是:

    21:18:39

    21:18:39

    #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);
    struct tm ptm = { 0 };
    struct tm ptmEnd = { 0 };
    localtime_r(&tNow, &ptm);
    localtime_r(&tEnd, &ptmEnd);

    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;
    }

    最后出来的结果是:

    10:29:06 
    10:59:06

     

    mysql_real_query也是非线程安全的

  • 相关阅读:
    关于图像分类问题读后感
    IO 输入流操作
    BP(back propagation)反向传播
    初识C++的类
    【转】贾扬清:希望Caffe成为深度学习领域的Hadoop
    转:谷歌大脑科学家 Caffe缔造者 贾扬清 微信讲座完整版
    cmd命令行给main传参数
    把vector中的string对象导入到字符指针数组中
    转:字符数组与字符指针
    MHI ,运动历史图像的的获取[下载自CSDN]
  • 原文地址:https://www.cnblogs.com/linmzh/p/2832022.html
Copyright © 2011-2022 走看看