C++11——多线程编程12 如何让线程在C++11中休眠

翻译来自:https://thispointer.com/how-to-put-a-thread-to-sleep-in-c11-sleep_for-sleep_until/

在本文中,我们将讨论如何让 c++11 线程休眠

c++11提供了2个让线程休眠的函数,即

std::this_thread::sleep_for
std::this_thread::sleep_until

沉睡一段时间

C++11提供了一个函数std::this_thread::sleep_for来阻塞当前进程指定的持续时间即

template <class Rep, class Period>
void sleep_for (const chrono::duration<Rep,Period>& rel_time);

此函数接受一个持续时间作为参数,并使调用线程在该特定持续时间内休眠。这个持续时间可以从纳秒到几小时,即

std::chrono::nanoseconds
std::chrono::microseconds
std::chrono::milliseconds
std::chrono::seconds
std::chrono::minutes
std::chrono::hours

让我们看一些例子,

 

为 MilliSeconds 休眠一个线程:

要让线程休眠 200 毫秒,请使用以下参数调用 sleep_for,即

std::this_thread::sleep_for(std::chrono::milliseconds(200));

使线程休眠几分钟:

要使线程休眠 1 分钟,请使用以下参数调用 sleep_for,即

std::this_thread::sleep_for(std::chrono::minutes(1));

 

例子

#include <iostream>
#include <thread>
#include <chrono>
void threadFunc()
{
    int i = 0;
    while (i < 10)
    {
        // Print Thread ID and Counter i
        std::cout<<std::this_thread::get_id()<<" :: "<<i++<<std::endl;
        // Sleep this thread for 200 MilliSeconds
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
}
int main()
{
    std::thread th(&threadFunc);
    th.join();
    return 0;
}

 

输出:

140484807997184 :: 0
140484807997184 :: 1
140484807997184 :: 2
140484807997184 :: 3
140484807997184 :: 4
140484807997184 :: 5
140484807997184 :: 6
140484807997184 :: 7
140484807997184 :: 8
140484807997184 :: 9

 

沉睡到某个时间点

很多时候我们希望线程休眠直到将来的某个时间点。这可以使用 sleep_untill() 来实现,即

template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleepTime );

它接受一个时间点作为参数并阻塞当前线程直到达到这个时间点。

查看完整的示例,在这里我们将让线程休眠直到将来的某个时间点,即

#include <iostream>
#include <thread>
#include <chrono>
// Print Current Time
void print_time_point(std::chrono::system_clock::time_point timePoint)
{
    std::time_t timeStamp = std::chrono::system_clock::to_time_t(timePoint);
    std::cout << std::ctime(&timeStamp) << std::endl;
}
void threadFunc()
{
    std::cout<<"Current Time :: ";
    // Print Current Time
    print_time_point(std::chrono::system_clock::now());
    // create a time point pointing to 10 second in future
    std::chrono::system_clock::time_point timePoint =
            std::chrono::system_clock::now() + std::chrono::seconds(10);
    std::cout << "Going to Sleep Until :: "; print_time_point(timePoint);
    // Sleep Till specified time point
    // Accepts std::chrono::system_clock::time_point as argument
    std::this_thread::sleep_until(timePoint);
    std::cout<<"Current Time :: ";
    // Print Current Time
    print_time_point(std::chrono::system_clock::now());
}
int main()
{
    std::thread th(&threadFunc);
    th.join();
    return 0;
}

 

 输出

Current Time :: Thu Nov 18 20:45:11 2021

Going to Sleep Until :: Thu Nov 18 20:45:21 2021

Current Time :: Thu Nov 18 20:45:21 2021

 

posted @ 2021-11-18 20:46  冰糖葫芦很乖  阅读(6430)  评论(0编辑  收藏  举报