Pause program execution for 5 seconds in c++

前端 未结 2 1084
醉梦人生
醉梦人生 2020-12-15 01:06

I want to pause the execution of c++ program for 5 seconds. In android Handler.postDelayed has the required functionality what I am looking for. Is there anything similar to

相关标签:
2条回答
  • 2020-12-15 01:45
    #include <iostream>
    #include <chrono>
    #include <thread>
    
    int main()
    {
        std::cout << "Hello waiter" << std::endl;
        std::chrono::seconds dura( 5);
        std::this_thread::sleep_for( dura );
        std::cout << "Waited 5s\n";
    }
    

    this_thread::sleep_for Blocks the execution of the current thread for at least the specified sleep_duration.

    0 讨论(0)
  • 2020-12-15 01:46

    You can do this on the pure C level, because C api calls are usable also from C++. It eliminiates the problem if you actual c++ library didn't contained the needed std:chrono or std::this_thread (they differ a little bit).

    The C api of most OSes contains some like a sleeping function, although it can be also different. For example, on posixen, there is the sleep() API call in the standard C library, and you can use this from C++ as well:

    #include <unistd.h>
    
    int main() {
       sleep(5);
       return;
    }
    

    Or you can use usleep() is you want a better precision as seconds. usleep() can sleep for microsecond precision.

    On windows, you can use the Sleep(int usec) call, which is with big 'S', and uses milliseconds.

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