Home > Backend Development > C++ > body text

How to Implement Sleep Functionality in C ?

Susan Sarandon
Release: 2024-10-24 00:31:29
Original
560 people have browsed it

How to Implement Sleep Functionality in C  ?

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 and headers, providing a cross-platform standard for thread manipulation. To pause the program for a specified number of milliseconds, the std::this_thread::sleep_for function can be employed.

<code class="cpp">#include <chrono>
#include <thread>

std::chrono::milliseconds timespan(111605); // or whatever

std::this_thread::sleep_for(timespan);</code>
Copy after login

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

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!

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
Latest Articles by Author
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!