使用条件变量的基于精确计时器的处理实现
我需要一个线程来准确地每秒执行一次处理。假设如果工作线程正忙于某些需要超过一秒的操作,我希望工作线程错过1s到期通知并在下一个周期执行处理。
我正在尝试使用两个线程来实现这一点。一个线程是工作线程,另一个线程休眠一秒并通过条件变量通知工作线程。
代码如下所示
工作线程
while(!threadExit){
std::unique_lock<std::mutex> lock(mutex);
// Block until a signal is received
condVar_.wait(lock, [this](){return (threadExit || performProc);)});
if(threadExit_){
break;
}
// Perform the processing
..............
}
定时器线程
while(!threadExit)
{
{
std::unique_lock<std::mutex> lock(mutex);
performProc= false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if(threadExit){
break;
}
{
std::unique_lock<std::mutex> lock(mutex);
performProc= true;
}
condVar.notify_one();
}
请注意,变量 threadExit 是由主线程在互斥锁下设置的,并通知给工作线程。计时器线程在唤醒时可以看到此标志(这对于我的实现来说应该没问题)
您认为在工作线程将其视为 true 之前 performProc 可能会再次设置为 false 吗?如果是,您能否说明如何解决这个问题?谢谢!
I need a thread to perform processing every one second accurately. Suppose if the worker thread is busy on some operation that takes more than one second, I want the worker thread to miss the 1s expiry notification and perform the processing in the next cycle.
I am trying to implement this using two threads. One thread is a worker thread, another thread sleeps for one second and notifies the worker thread via condition variable.
Code is shown below
Worker thread
while(!threadExit){
std::unique_lock<std::mutex> lock(mutex);
// Block until a signal is received
condVar_.wait(lock, [this](){return (threadExit || performProc);)});
if(threadExit_){
break;
}
// Perform the processing
..............
}
Timer thread
while(!threadExit)
{
{
std::unique_lock<std::mutex> lock(mutex);
performProc= false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if(threadExit){
break;
}
{
std::unique_lock<std::mutex> lock(mutex);
performProc= true;
}
condVar.notify_one();
}
Please note the variable threadExit is set by the main thread under the mutex lock and notified to worker thread. The timer thread can see this flag when it wakes up(which should be fine for my implementation)
Do you think performProc may set to false again before the worker thread sees it as true? If yes, can you please throw some light on how to tackle this problem? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非
threadExit
是atomic
,否则代码会表现出未定义的行为(竞争条件)。对threadExit
的所有访问都必须受到互斥锁的保护,因此还要读取while(!threadExit)
和if(threadExit)...
。但没有必要这样做。如果使用
sleep_until
<,则可以在同一线程中运行所有内容/a> (和稳定的时钟)而不是sleep_for
。输出:
Unless
threadExit
isatomic
, the code exhibits undefined behavior (race condition). All accesses tothreadExit
must be protected by a mutex, so also reads inwhile(!threadExit)
andif(threadExit)...
.But there's no need to do any of this. You can run everything in the same thread if you use
sleep_until
(and a steady clock) instead ofsleep_for
.Output: