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.
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.
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.
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