Home > Backend Development > C++ > body text

How to Suspend Execution in C : A Guide to the Sleep Function and Alternatives

DDD
Release: 2024-10-23 19:50:02
Original
455 people have browsed it

How to Suspend Execution in C  : A Guide to the Sleep Function and Alternatives

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

Additional Functionality:

In addition to sleep_for, the header provides sleep_until to pause execution until a specific time point. This offers more flexibility and allows for more precise control over the sleep duration.

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!