Sleep Functionality in C
In C , developers often encounter the need to pause program execution for a specific duration, similar to the Sleep() function in other programming languages. This article aims to address that requirement and provide comprehensive solutions.
std::this_thread::sleep_for
C 11 introduced the
<code class="cpp">#include <chrono> #include <thread> std::chrono::milliseconds timespan(111605); // or whatever std::this_thread::sleep_for(timespan);</code>
std::this_thread::sleep_until
An alternative to std::this_thread::sleep_for is std::this_thread::sleep_until, which allows pausing until a specific point in time is reached.
Pre-C 11 Solutions
Before C 11, C lacked thread capabilities and sleep functionality. As such, platform-dependent solutions were necessary. Here's an example that works for both Windows and Unix:
<code class="cpp">#ifdef _WIN32 #include <windows.h> void sleep(unsigned milliseconds) { Sleep(milliseconds); } #else #include <unistd.h> void sleep(unsigned milliseconds) { usleep(milliseconds * 1000); // takes microseconds } #endif</code>
Alternatively, boost::this_thread::sleep can be used as a simpler pre-C 11 approach.
The above is the detailed content of How to Implement Sleep Functionality in C ?. For more information, please follow other related articles on the PHP Chinese website!