0

I have a problem with the nanosleep() function.

In a test project, it works as expected.
In the real project, it does not: it is like if the sleeping time was zero.

As far as I can see, the biggest difference between the test and the real project is the number of threads: one in the test, two in the real one.

Could this be the reason?

If I put the nanosleep call in the code run by one thread, shouldn't that thread pause?

Thank you.

4

2 に答える 2

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 に答える