C++11 chrono 库 - 如何在特定时间间隔后执行方法?

C++11 chrono library - How to execute method after a specific time interval?

我想正确使用 chrono 库来配置我的 class 以在几毫秒后调用一个方法。

#include <iostream>
#include <chrono>
#include <ctime>

Class House
{
private:
   //...
public:
   House() {};
   ~House() {};

   void method1() { std::cout << "method1 called" << std::endl; };
   void method2() { std::cout << "method2 called" << std::endl; };
   void method3() { std::cout << "method3 called" << std::endl; };
};

int main
{
   House h;

   //For the object 'h', I need to call method1() after 100ms
   // ???

   //For the object 'h', I need to call method2() after 200ms
   // ???

   //For the object 'h', I need to call method3() after 300ms
   // ???

   return 0;
}

知道怎么做吗?

这是我刚接触 C++ 以来一直在阅读/学习的一本书的片段。 (我大约 3 个月前开始,但在那之前我练习了 Java 和 Python 一点。)这解释了如何做你打算做的事情以及一个例子来展示。我本可以用自己的话来解释的;不过我觉得这句话一针见血:

5.3.4.1 Waiting for Events

Sometimes, a thread needs to wait for some kind of external event, such as another thread completing a task or a certain amount of time having passed. The simplest “event” is simply time passing. Consider:

auto t0 = high_resolution_clock::now();
this_thread::sleep_for(milliseconds{20}); 
auto t1 = high_resolution_clock::now();
cout << duration_cast<nanoseconds>(t1 - t0).count() << " nanoseconds passed\n";

Note that I didn't even have to launch a thread; by default, this_thread refers to the one and only thread (§ 42.2.6). I used duration_cast to adjust the clock’s units to the nanoseconds I wanted. See § 5.4.1 and § 35.2 before trying anything more complicated than this with time. The time facilities are found in <chrono>.

— The C++ Programming Language 4th Edition by Bjarne Stroustrup

我觉得使用这种方法似乎有助于完成您想要做的事情:一个接一个地完成任务。查看 <chrono>。我找到这个答案是因为我正在阅读一本书,这不是我的作品,而是来自一本书。如果您打算同时处理许多任务 运行,您将需要创建线程,如果它们碰巧共享资源,您可能需要锁或只使用 unique_lock / lock_guard。我更喜欢 unique_lock.