-
2022-04-08 17:56:15
使用说明
std::this_thread::sleep_for函数是C11的休眠函数,表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。
由于是一个跨平台的函数,因此在代码中大量应用,避免了在不同平台之间所以通过宏定义编译问题。在windows下,可以简单替代Sleep, 在Linux下,替代usleep
调用例子
头文件定义: #include <thread> std::this_thread::sleep_for(std::chrono::milliseconds(1000));//睡眠1000毫秒(1秒) 等同: std::chrono::milliseconds dura(1000); std::this_thread::sleep_for(dura);
boost sleep_for
基本作用跟std::this_thread::sleep_for是一样的
头文件定义:#include <boost/thread.hpp>
调用例子:boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));//延时1秒
注意
1)异常情况:如果将时间修改为过去的时间,该函数会一直阻塞,直到机器时间重新走到修改前的时间,才会唤醒线程。例如当前时间是10:30,修改时间为10:20, sleep_for函数会一直阻塞,直到时间重新走到10:30才重新唤醒。将时间修改为将来的时间,没有问题。并且使用Sleep函数在任何情况下也没有问题,跟系统时间没有关系。总结:如果系统的时间来回跳变,会影响到sleep_for函数的正常唤醒,从而影响到调用该函数线程的执行状况,并且是上述两种函数都有这个问题
使用经验:最好在各自库创建线程中调用对应的函数,std::thread调用std::this_thread::sleep_for函数,boost::thread调用boost::this_thread::sleep_for
2)在gcc中使用这个函数时,需要再编译的时候加-D_GLIBCXX_USE_NANOSLEEP选项,否则报语法错误
更多相关内容 -
c++ 之 std::this_thread::yield 与std::this_thread::sleep_for
2018-11-30 11:03:20std::this_thread::yield: 当前线程放弃执行,...std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。 this_thread 包装了一组可以访问当前...std::this_thread::yield: 当前线程放弃执行,操作系统调度另一线程继续执行。即当前线程将未使用完的“CPU时间片”让给其他线程使用,等其他线程使用完后再与其他线程一起竞争"CPU"。
std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。this_thread 包装了一组可以访问当前线程信息的函数
1、get_id() 获取当前线程的id。
// thread::get_id / this_thread::get_id #include <iostream> // std::cout #include <thread> // std::thread, std::thread::id, std::this_thread::get_id #include <chrono> // std::chrono::seconds std::thread::id main_thread_id = std::this_thread::get_id(); void is_main_thread() { if ( main_thread_id == std::this_thread::get_id() ) std::cout << "This is the main thread.\n"; else std::cout << "This is not the main thread.\n"; } int main() { is_main_thread(); std::thread th (is_main_thread); th.join(); }
输出结果This is the main thread. This is not the main thread.
2、yield()
调用线程放弃执行,回到准备状态,重新分配cpu资源。所以调用该方法后,可能执行其他线程,也可能还是执行该线程// this_thread::yield example #include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::yield #include <atomic> // std::atomic std::atomic<bool> ready (false); void count1m(int id) { while (!ready) { // wait until main() sets ready... std::this_thread::yield(); } for (volatile int i=0; i<1000000; ++i) {} std::cout << id; } int main () { std::thread threads[10]; std::cout << "race of 10 threads that count to 1 million:\n"; for (int i=0; i<10; ++i) threads[i]=std::thread(count1m,i); ready = true; // go! for (auto& th : threads) th.join(); std::cout << '\n'; return 0; }
输出结果race of 10 threads that count to 1 million... 6189370542
3、template <class Clock, class Duration>
void sleep_until (const chrono::time_point<Clock,Duration>& abs_time);
阻塞调用线程,一直到指定事件// this_thread::sleep_for example #include <iostream> // std::cout #include <iomanip> // std::put_time #include <thread> // std::this_thread::sleep_until #include <chrono> // std::chrono::system_clock #include <ctime> // std::time_t, std::tm, std::localtime, std::mktime int main() { using std::chrono::system_clock; std::time_t tt = system_clock::to_time_t (system_clock::now()); struct std::tm * ptm = std::localtime(&tt); std::cout << "Current time: " << std::put_time(ptm,"%X") << '\n'; std::cout << "Waiting for the next minute to begin...\n"; ++ptm->tm_min; ptm->tm_sec=0; std::this_thread::sleep_until (system_clock::from_time_t (mktime(ptm))); std::cout << std::put_time(ptm,"%X") << " reached!\n"; return 0; }
输出结果Current time: 11:52:36 Waiting for the next minute to begin... 11:53:00 reached!
4、template <class Rep, class Period>
void sleep_for (const chrono::duration<Rep,Period>& rel_time);
阻塞调用线程,一直到指定时间段后。// this_thread::sleep_for example #include <iostream> // std::cout #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds int main() { std::cout << "countdown:\n"; for (int i=10; i>0; --i) { std::cout << i << '\n'; std::this_thread::sleep_for (std::chrono::seconds(1)); } std::cout << "Lift off!\n"; return 0; }
输出结果countdown: 10 9 8 7 6 5 4 3 2 1 Lift off!
参考链接:
https://en.cppreference.com/w/cpp/thread/sleep_for
-
std::this_thread::sleep_for 与std::this_thread::yield的区别
2018-10-30 12:19:40std::this_thread::yield: 当前...std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。 两者具有相似的作用,但使用目的不同。例如以下两个...std::this_thread::yield: 当前线程放弃执行,操作系统调度另一线程继续执行。即当前线程将未使用完的“CPU时间片”让给其他线程使用,等其他线程使用完后再与其他线程一起竞争"CPU"。
std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。两者具有相似的作用,但使用目的不同。例如以下两个函数:
#include<thread> #include<mutex> #include<iostream> std::mutex mtx; bool g_flag = false; void F1(int n) { while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); n++; if(n == 10){ mtx.lock(); g_flag = true; mtx.unlock(); }else std::cout<<"F1 n: "<<n<<std::endl; } } void F2(int& n) { while (true) { mtx.lock(); bool flag = g_flag; mtx.unlock(); if( flag ) { n++; std::cout<<"F2 n: "<<n<<std::endl; }else std::this_thread::yield(); } } int main(){ int n = 0; std::thread t1(F1, n), t2(F2, std::ref(n)); t1.join(); t2.join(); }
F1线程函数循环体内,每隔1秒钟执行一次操作。
F2线程函数循环体内若标志位被置位则执行一次操作,否则放弃当前线程,让出未用完的CPU时间片,等其他线程使用完后再一起竞争CPU时间,若循环体内不使用yield,则该线程立即与其他线程竞争CPU时间,像此类线程频繁地竞争CPU时间从而影响程序性能。
-
std::this_thread::sleep_for
2020-03-01 10:07:54std::this_thread::sleep_for Defined in header <thread> - 定义于头文件 <thread> 1. std::this_thread::sleep_for template <class Rep, class Period> void sleep_for (const chrono::...std::this_thread::sleep_for
Defined in header
<thread>
- 定义于头文件<thread>
1.
std::this_thread::sleep_for
template <class Rep, class Period>
void sleep_for (const chrono::duration<Rep,Period>& rel_time);
阻塞当前线程执行,至少经过指定的
sleep_duration
。此函数可能阻塞长于
sleep_duration
,因为调度或资源争议延迟。标准库建议用稳定时钟度量时长。若实现用系统时间代替,则等待时间亦可能对时钟调节敏感。
Sleep for time span - 睡眠一段时间
Blocks execution of the calling thread during the span of time specified by
rel_time
.
在rel_time
指定的时间段内阻止调用线程的执行。The execution of the current thread is stopped until at least rel_time has passed from now. Other threads continue their execution.
当前线程的执行将停止,直到从现在起至少经过rel_time
为止。其他线程继续执行。2. Parameters
rel_time
The time span after which the calling thread shall resume its execution.
调用线程应在其后恢复执行的时间间隔。Note that multi-threading management operations may cause certain delays beyond this.
请注意,多线程管理操作可能会导致某些延迟。duration is an object that represents a specific relative time.
持续时间是代表特定相对时间的对象。要睡眠的时长。
resume [rɪ'zjuːm]:n. 简历 v. 继续,重返
3. Return value
none
4. Examples
4.1
std::this_thread::sleep_for
//============================================================================ // Name : std::this_thread::sleep_for // Author : Yongqiang Cheng // Version : Version 1.0.0 // Copyright : Copyright (c) 2019 Yongqiang Cheng // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> // std::cout, std::endl #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds int main() { std::cout << "countdown:\n"; for (int i = 10; i > 0; --i) { std::cout << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "Lift off!\n"; return 0; }
Output (after 10 seconds):
countdown: 10 9 8 7 6 5 4 3 2 1 Lift off!
4.2
std::this_thread::sleep_for
//============================================================================ // Name : std::this_thread::sleep_for // Author : Yongqiang Cheng // Version : Version 1.0.0 // Copyright : Copyright (c) 2019 Yongqiang Cheng // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> // std::cout, std::endl #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds int main() { using namespace std::chrono_literals; std::cout << "Hello waiter\n" << std::flush; // C++14 auto start = std::chrono::high_resolution_clock::now(); std::this_thread::sleep_for(2s); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed = end - start; std::cout << "Waited " << elapsed.count() << " ms\n"; return 0; }
10:22:39 **** Incremental Build of configuration Debug for project hello_world **** make all Building file: ../src/hello_world.cpp Invoking: GCC C++ Compiler g++ -std=c++1y -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/hello_world.d" -MT"src/hello_world.o" -o "src/hello_world.o" "../src/hello_world.cpp" Finished building: ../src/hello_world.cpp Building target: hello_world Invoking: GCC C++ Linker g++ -o "hello_world" ./src/hello_world.o -lpthread Finished building target: hello_world 10:22:40 Build Finished (took 895ms)
Hello waiter Waited 2000.06 ms
7. Exception safety - 异常安全性
If the type of
rel_time
never throws exceptions (like the instantiations of duration in header<chrono>
), this function never throws exceptions (no-throw guarantee).
如果rel_time
的类型从不抛出异常 (如头文件<chrono>
中的 duration` 实例化),则此函数从不抛出异常 (无抛出保证)。assignment [ə'saɪnmənt]:n. 任务,布置,赋值
References
http://www.cplusplus.com/reference/thread/this_thread/sleep_for/
https://en.cppreference.com/w/cpp/thread/sleep_for -
C++11 std::this_thread::sleep_for让我睡一会再干活
2021-03-28 18:13:53我当时以为sleep会导致什么调度问题,后来上网查了下,发现原来不是,std::this_thread::sleep_for只不过是C++11 标准对各个平台的睡眠函数的封装,因为sleep是平台相关的api,它是类UNIX系统提供的,换 -
std::this_thread::sleep_for和直接使用sleep有什么区别?
2020-07-16 10:00:28问题如题 std::this_thread::sleep_for(std::chrono::seconds(1));和Sleep(1000)有区别吗? 请详细讲讲。为啥要用std::this_thread? -
c++之std::unique_lock, std::lock, std::scoped_lock及std::condition_variable
2022-01-28 17:22:26cpp_reference_std::scoped_lock cpp_reference_std::unique_lock scope_lock与lock_guard区别 std::lock_guard or std::scoped_lock C++多线程unique_lock详解 -
C++11 std::this_thread
2019-01-22 08:08:48std::this_thread是一个命名空间,包含一系列访问当前线程的函数。 二 4个函数 1 get_id noexcept 获取线程id。 2 yield noexcept 当前线程放弃执行,给实现重新调度的机会,允许其他线程运行,该线程回到准备... -
c++ std::enable_shared_from_this
2020-11-21 11:33:02在很多应用中,我们可能希望对象永远都存在,特别是在一些异步执行的程序中,回调函数的传入是需要保证对象指针的有效性的,所以,我们一般都是传入共享指针,我们就用到了std::enable_shared_from_this,这样可以... -
C++ std::this_thread知识整理
2020-11-03 18:27:27std::this_thread::sleep_for () std::this_thread::sleep_until () 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 例如:第一章 Python 机器学习入门之pandas的使用 提示:写完文章后,... -
std::this_thread
2020-02-06 18:17:59Interface get_id ...Interface sleep_for std::this_thread里有 访问 当前线程的 接口函数. Interface get_id 函数原型: thread::id get_id() noexpect; // 返回 calling thread的 thread i... -
c++11:智能指针之std::unique_ptr、std::shared_ptr、std::weak_ptr
2020-11-24 11:04:011、std::unique_ptr 声明: template<class T,class Deleter = std::default_delete<T>> class unique_ptr; template <class T,class Deleter> class unique_ptr<T[], Deleter>; std:... -
‘sleep_for’ is not a member of ‘std::this_thread’
2018-10-26 11:56:32sleep_for(const chrono::duration<_Rep, _Period>& __rtime) { chrono::seconds __s = chrono::duration_cast<chrono::seconds>(__rtime); chrono::nanoseconds __ns = chrono::duration_cast<chrono::... -
C++11中std::packaged_task的使用
2020-01-31 19:53:45C++11中的std::packaged_task是个模板类。std::packaged_task包装任何可调用目标(函数、lambda表达式、bind表达式、函数对象)以便它可以被异步调用。它的返回值或抛出的异常被存储于能通过std::future对象访问的共享... -
[原]C++新标准之std::chrono::time_point
2019-10-08 05:46:27原总结STL标准库chronotime_pointratio概览类定义总结思考拓展system_clocksteady_clockhigh_resolution_...chrono>文件中,用来表示时间点。 类定义 关键代码摘录如下(格式有调整): template<class _... -
std::condition_variable与std::unique_lock的结合使用
2021-11-16 10:19:29std::mutex mutex; std::condition_variable cv; // 条件变量与临界区有关,用来获取和释放一个锁,因此通常会和mutex联用。 std::unique_lock lock(mutex); // 此处会释放lock,然后在cv上等待,直到其它线程通过... -
std::chrono时间库详解
2021-04-21 09:37:24主要时间类型 std::ratio<num, den> 定义分式(std::ratio模板请参考《C++新标准之std::ratio》),例如: std::ratio<60, 1> minutes;... std::ratio<... std::ratio<...chrono命名 -
C++时间类 std::chrono
2022-04-15 09:50:31std::chrono -
C++ std::this_thread
2019-09-01 17:28:59this_thread -
C++11中std::shared_future的使用
2020-01-30 20:58:29C++11中的std::shared_future是个模板类。与std::future类似,std::shared_future提供了一种访问异步操作结果的机制;不同于std::future,std::shared_future允许多个线程等待同一个共享状态;不同于std::future仅... -
std::future和std::promise和std::packaged_task
2021-03-25 09:05:12std::future 其实future有两个兄弟,一个是std::future, 一个是它大哥std::shared_future。他们的区别就是std::future只支持移动语义,它所引用的共享状态不与另一异步返回对象共享。换成人话就是如果你想在多个... -
std::chrono时间
2020-01-20 10:27:21c++11的时间库chrono均位于名字空间std::chrono下。 命名空间:using namespace std::chrono; 宏定义: #define _XTIME_NSECS_PER_TICK 100 #define _XTIME_TICKS_PER_TIME_T (long long)10000000 时钟 c... -
C++11如何通过std::uinque_lock和std::timed_mutex 使用try_lock_for
2019-03-05 23:04:14C++11如何通过std::uinque_lock和std::timed_mutex 使用try_lock_for 关于mutex,我个人感觉在cnblogs上有一个写的比较好: link: 其作者的github地址为: link: 其实就是在unique_lock的构造函数加上std::defer_... -
C++11 std::chrono::duration
2020-08-14 15:42:44[原]C++新标准之std::chrono::duration 原总结C++11...c++新标准提供了新的线程库,最近在写测试代码的时候需要让当前线程休眠,之前直接调用windows提供的Sleep()就好了,新标准中可以使用std::this_... -
c++中 std::this_thread整理
2019-01-06 13:03:03在C++11中提供了sdt::thread,可以很方便的让我们对当前的线程进行管理。其中提供了四个成员函数,使用方法和注意事项见代码 #include <thread> #include <chrono> #include <... -
std::future、std::promise、std::packaged_task、std::async
2021-09-14 14:50:29#include <...thread> #include <chrono> #include <condition_variable> #include <hash_map> #include <unordered_map> using namespace std; // 使用std::promise.