What Can I Use Besides usleep in a Modern POSIX Environment?

前端 未结 5 1565
一向
一向 2021-01-19 05:04

I\'m fairly new to C but writing a small multithreaded application. I want to introduce a delay to a thread. I\'d been using \'usleep\' and the behavior is what I desire -

相关标签:
5条回答
  • 2021-01-19 05:48

    From the manual page: This function is obsolete. Use nanosleep instead.

    0 讨论(0)
  • 2021-01-19 05:54

    The problem is that you are using a standard C99 compiler, but you're trying to access POSIX extensions. To expose the POSIX extensions you should for example define _POSIX_C_SOURCE to 200809L (for the current standard). For example this program:

    #include <time.h>
    
    int main(void) {
            struct timespec reqtime;
            reqtime.tv_sec = 1;
            reqtime.tv_nsec = 500000000;
            nanosleep(&reqtime, NULL);
    }
    

    will compile correctly and wait for 1.5 seconds (1 second + 500000000 nanoseconds) with the following compilation command:

    c99 main.c -D _POSIX_C_SOURCE=200809L
    

    The _POSIX_C_SOURCE macro must be defined with an appropriate value for the POSIX extensions to be available.

    Also the options -Wall, -pedantic and -W are not defined for the POSIX c99 command, those look more like gcc commands to me (if they work on your system then that's fine, just be aware that they are not portable to other POSIX systems).

    0 讨论(0)
  • 2021-01-19 06:02

    implicit declaration of function ‘usleep’

    This warning usually means that you didn't #include the right header file, in this case unistd.h.

    0 讨论(0)
  • 2021-01-19 06:06

    You are probably on a modern POSIX system:

    POSIX.1-2008 removes the specification of usleep().

    On my system (linux) there is a detailed explanation of the macros that must be set to get that function back. But you should just follow the advice that zvrba already gave, use nanosleep instead.

    0 讨论(0)
  • 2021-01-19 06:09

    Did you have the #include <unistd.h> ?.

    And you can use some of the similar methods instead: nanosleep() for nanoseconds and sleep() for seconds. Or another way could be using clock(), but i think this is more CPU wasting.

    0 讨论(0)
提交回复
热议问题