"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Pause Program Execution in C++ using Sleep Functions?

How to Pause Program Execution in C++ using Sleep Functions?

Published on 2024-10-31
Browse:727

How to Pause Program Execution in C   using Sleep Functions?

Seeking a Sleep Function in C

In pursuit of controlling program execution flow, you may encounter the need to pause the program for a specified duration. In C , there's no direct equivalent to the commonly used Sleep(time) function found in other languages. However, the C standard library provides a viable alternative.

Introducing std::this_thread::sleep_for

The C Standard Library offers the std::this_thread::sleep_for function, which allows you to suspend the current thread's execution for a specified duration. To use it, you'll need to include the following headers:

#include 
#include 

The syntax of std::this_thread::sleep_for is as follows:

void sleep_for(const std::chrono::duration& timespan);

Where timespan is a std::chrono::duration object specifying the duration of the sleep. To create a millisecond-based std::chrono::duration, use the std::chrono::milliseconds constructor:

std::chrono::milliseconds timespan(111605);

Using these components, you can halt the execution of your program for the desired time interval:

std::this_thread::sleep_for(timespan);

Note that std::this_thread::sleep_until serves as a complementary function for precise time-based synchronization.

Legacy Sleep Options (Pre-C 11)

Prior to the introduction of C 11, the language lacked thread functionality and sleep capabilities. Consequently, the solution to suspend execution was platform-dependent. For Windows or Unix, you might have relied on something like this:

#ifdef _WIN32
    #include 
    
    void sleep(unsigned milliseconds)
    {
        Sleep(milliseconds);
    }
#else
    #include 
    
    void sleep(unsigned milliseconds)
    {
        usleep(milliseconds * 1000); // takes microseconds
    }
#endif

Alternatively, you could have simplified the implementation using the Boost library's boost::this_thread::sleep.

Release Statement This article is reprinted at: 1729677484 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3