Sleep Function in C : A Comprehensive Guide
Unlike its counterpart in C, C lacks an explicit Sleep() function to pause program execution for a specified duration. However, the modern C standard introduces a versatile solution, provided by the
Using std::this_thread::sleep_for:
This is the recommended approach for C 11 and later. It takes a single argument of type std::chrono::milliseconds to specify the sleep duration.
<code class="cpp">#include <chrono> #include <thread> std::chrono::milliseconds timespan(111605); // or whatever std::this_thread::sleep_for(timespan);</code>
Pre-C 11 Alternatives:
Prior to the introduction of threading in C 11, platform-specific solutions were necessary. One option is to define a sleep function using conditional compilation:
<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, you can leverage the Boost library:
<code class="cpp">#include <boost/thread/thread_only.hpp> void sleep(unsigned milliseconds) { boost::this_thread::sleep(boost::posix_time::milliseconds(milliseconds)); }</code>
Additional Functionality:
In addition to sleep_for, the
The above is the detailed content of How to Suspend Execution in C : A Guide to the Sleep Function and Alternatives. For more information, please follow other related articles on the PHP Chinese website!