c - 时间相关函数和多线程

标签 c linux multithreading time

我在 Linux(带有 libc-2.12.so 的 CentOS 6.3 发行版)上工作。

我想知道C库函数time()localtime()mktime()是否可以在多线程环境下使用。

仅举个例子(不一定是我的项目代码):

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

int main()
{

  time_t timep;

  struct tm *p;

  for (int i = 0; i < 1000; ++i)
  {
    time(&timep);
    printf("time() : %d \n", timep);
    p = localtime(&timep);
    timep = mktime(p);

    printf("time()->localtime()->mktime():%d\n", timep);
  }

  return 0;    
}

如果我用 OpenMP 包装上面的代码会怎样?也就是放在多线程环境下。

#include <stdio.h>  
#include <time.h>
#include <omp.h>

int main()
{

  time_t timep;

  struct tm *p;

#pragma omp parallel for
  for (int i = 0; i < 1000; ++i)
  {
    time(&timep);
    printf("time() : %d \n", timep);
    p = localtime(&timep);
    timep = mktime(p);

    printf("time()->localtime()->mktime():%d\n", timep);
  }

  return 0;
}

最佳答案

来自 manual localtime :

The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available since libc 5.2.5.

关于c - 时间相关函数和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18348383/

相关文章:

c - 为什么这个 C 程序打印输出 "10"而不管 for 循环?

mysql - 在 Ubuntu 上使用 APT 安装的 MySQL 的 BASEDIR 在哪里?

Java 多线程峰值处理器使用率

java - 何时线程。何时不使用线程

c - 取消引用指针作为 C 中的参数的目的

c - 如何比较两个数字,看看哪个更大

c - 帮助实现快速排序

java - 如何将 Netbeans 项目(使用 Java DB)从 Windows 迁移到 Linux?

c++ - QMYSQL 驱动未加载 Qt 5.6 Linux Ubuntu 16.04

基于Java套接字的文件传输应用程序客户端在调试时运行,但在正常运行时失败