Cross platform Sleep function for C++

后端 未结 7 1404
花落未央
花落未央 2020-12-05 04:28

Is it possible with macros make cross platform Sleep code? For example

#ifdef LINUX
#include 
#endif
#ifdef WINDOWS
         


        
相关标签:
7条回答
  • 2020-12-05 05:14

    Yes there is. What you do is wrap the different system sleeps calls in your own function as well as the include statements like below:

    #ifdef LINUX
    #include <unistd.h>
    #endif
    #ifdef WINDOWS
    #include <windows.h>
    #endif
    
    void mySleep(int sleepMs)
    {
    #ifdef LINUX
        usleep(sleepMs * 1000);   // usleep takes sleep time in us (1 millionth of a second)
    #endif
    #ifdef WINDOWS
        Sleep(sleepMs);
    #endif
    }
    

    Then your code calls mySleep to sleep rather than making direct system calls.

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