简体   繁体   English

std :: condition_variable :: wait_until对std :: this_thread :: sleep_for有什么好处吗?

[英]Does std::condition_variable::wait_until have any advantage against std::this_thread::sleep_for?

In a time waiting scenario: 在等待时间的情况下:

our software works in the background, and synchronizes data with the server in every 20 - 30 minutes. 我们的软件在后台运行,并且每隔20-30分钟与服务器同步数据。

I wanted to use 我想用

std::this_thread::sleep_for

But my superior strongly against any form of sleep function. 但我的上司强烈反对任何形式的睡眠功能。 He recommends 他建议

std::condition_variable::wait_until(lock, timeout-time, pred)

I wonder if there are any disadvantage for sleep_for under such scenario? 我想知道在这种情况下sleep_for是否有任何不利之处?

As pointed out in the comments already, it depends only on your usecase. 正如评论中已经指出的那样,它仅取决于您的用例。 The main difference between the two is, that condition_variable can wake up earlier if you trigger it. 两者之间的主要区别在于,如果触发它, condition_variable 可以提前唤醒。 You also can add a predicate that must be satisfied in order to actually wake up, but that's only a quality of life addition. 您还可以添加一个必须满足的谓词才能实际唤醒,但这只是一种生活品质的补充。 And btw, the equivalent to sleep_for is wait_for and not wait_until . 顺便说一下, sleep_for的等价物是wait_for而不是wait_until condition_variable is also great to communicate or synchronize between multiple threads. condition_variable也很适合在多个线程之间进行通信或同步。

Given everything you said, I would use condition_variable for the following reasons: 鉴于你所说的一切,我会使用condition_variable ,原因如下:

  1. Putting a thread to sleep for longer periods of time is not a good idea because your application can exit at any time (or rather can be requested to exit). 让线程长时间休眠并不是一个好主意,因为您的应用程序可以随时退出(或者可以请求退出)。 In that case you probably want your thread to exit properly, so you have to be able to wake it up at any time. 在这种情况下,您可能希望您的线程正确退出,因此您必须能够随时将其唤醒。
  2. You want to change the config on the fly. 您想要动态更改配置。 If your thread has to restart with new parameters or if you need that thread to actually load the config file you also don't want to wait for the next 20min intervall to end. 如果您的线程必须使用新参数重新启动,或者如果您需要该线程来实际加载配置文件,您也不希望等待下一个20分钟的intervall结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM