c++ - Any Time 函数保证调用返回不同的值

标签 c++ linux multithreading

我正在寻找一个时间函数,它保证为不同的调用返回不同的值。我在 LINUX 上尝试了以下方法,却发现这不是我想要的,它可能会为来自不同线程的调用返回相同的值。

   long GetTickCount()        
   {          
        struct timespec now;
        clock_gettime(MONOTONIC, &now);
        return now.tv_sec * 1000000000LL + now.tv_nsec;
   }

在 LINUX 上还有其他方法可以做到这一点吗?

最佳答案

任何时钟都将具有有限的粒度,这可能会导致连续调用返回相同的值。为了解决这个问题,您需要使用全局计数器:

static long long previous_time = 0;

long long get_strictly_monotonic_time() {
    int rc;
    struct timespec tp;
    long long t;
    rc = clock_gettime(CLOCK_MONOTONIC, &tp);
    if(rc < 0) return -1;
    t = tp.tv_sec * 1000000000LL + tp.tv_nsec;
    /* Critical region */
    if(t <= previous_time)
        t = previous_time + 1;
    previous_time = t;
    /* End of critical region */
    return t;
}

由于您希望它在多线程中可靠,因此您需要使用全局互斥锁(上面带有“临界区域”注释的区域)来保护全局计数器。

关于c++ - Any Time 函数保证调用返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771606/

相关文章:

c# - C++-STL映射和Boost的unordered_map的更好替代方案?

linux - Linux中的合并和对齐线

java - FileInputStream reading/dev/hda1 会有效地读取磁盘扇区吗

c# - C# 中的静态构造函数死锁是否与 ECMA CLI 标准相矛盾?

multithreading - 线程安全删除链表节点,使用细粒度方法

java - 在不同的线程中使用 swing

c++ - 运行时和融合序列之间的交互

c++ - SFML Project microsoft visual express 2010 到 2012 兼容性问题

C++ - 来自 std::string 的意外输出

打开 Outlook 并发送电子邮件的 PHP 代码