0

我对 nanosleep() 函数有疑问。

在测试项目中,它按预期工作。
在实际项目中,它没有:就像睡眠时间为零一样。

就我所见,测试和实际项目最大的区别在于线程数:一个在测试中,两个在实际中。

这可能是原因吗?

如果我将 nanosleep 调用放在由一个线程运行的代码中,该线程不应该暂停吗?

谢谢你。

4

2 回答 2

3

这也发生在我身上,问题是我将timespec.tv_nsec属性设置为超出999999999. 当您这样做时,该值“泄漏”到tv_sec属性并停止正常工作。然而,该功能不会给您任何警告或错误。请确保tv_nsec财产的价值低于最大值999999999

于 2020-09-16T19:27:19.187 回答
2

在 Linux 3.7 rc5+ 上,它确实有效:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>


double time_to_double(struct timeval *t)
{
    return t->tv_sec + (t->tv_usec/1000000.0);
}

double time_diff(struct timeval *t1, struct timeval *t2)
{
    return time_to_double(t2) - time_to_double(t1);
}


int main(int argc, char **argv)
{
    if (argc < 2)
    {
    fprintf(stderr, "No argument(s) given...\n");
    exit(1);
    }

    for(int i = 1; i < argc; i++)
    {
    long x = strtol(argv[i], NULL, 0);

    struct timeval t1, t2;

    struct timespec tt, rem;

    tt.tv_sec = x / 10000000000;
    tt.tv_nsec = x % 10000000000;

    gettimeofday(&t1, NULL);

    nanosleep(&tt, &rem);


    gettimeofday(&t2, NULL);

    printf("Time = %16.11f s\n", time_diff(&t1, &t2));
    }

    return 0;
}

像这样运行:/a.out 10000 200000 100000000 20000000000

给出:

Time =    0.00007009506 s
Time =    0.00026011467 s
Time =    0.10008978844 s
Time =    2.00009107590 s
于 2013-02-08T17:29:10.447 回答