Home > Backend Development > C++ > body text

How to Pause Execution in C for a Specified Duration?

DDD
Release: 2024-10-24 04:28:02
Original
819 people have browsed it

How to Pause Execution in C   for a Specified Duration?

Sleep Function in C

Problem:

In C , how can you pause a program for a specified duration in milliseconds, similar to Sleep(time); in other languages?

Header and Function Signature:

To facilitate sleeping in C , include the and headers. The function to use is:

<code class="cpp">std::this_thread::sleep_for(std::chrono::milliseconds timespan);</code>
Copy after login

Solution:

To pause the program for a specific amount of time, use the following syntax:

<code class="cpp">std::chrono::milliseconds timespan(111605); // or any desired time
std::this_thread::sleep_for(timespan);</code>
Copy after login

Historical Sleep Functions:

Prior to C 11, C lacked thread and sleep capabilities. The following platform-dependent solution was utilized:

<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, a simpler pre-C 11 option was to use boost::this_thread::sleep.

The above is the detailed content of How to Pause Execution in C for a Specified Duration?. 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