什么时候使用pthread屏障而不是条件等待和广播更合适
When is it more appropriate to use a pthread barrier instead of a condition wait and broadcast?
我正在用C++编写遥测系统,在将某些线程与标准pthread_cond_timedwait和pthread-cond_broadcast同步时遇到了一些困难。
问题是,我需要一些方法来让正在进行广播的函数知道是否有另一个线程对广播进行了操作。
经过一番认真的搜索,我决定可以尝试为这两个线程使用屏障。但是,我仍然想要pthread_cond_timedwait的超时功能。
这基本上是我想到的:(然而感觉太过分了)
侦听功能:检查一段毫秒的时间,以查看当前是否正在触发事件。
bool listen(uint8_t eventID, int timeout)
{
int waitCount = 0;
while(waitCount <= timeout)
{
globalEventID = eventID;
if(getUpdateFlag(eventID) == true)
{
pthread_barrier_wait(&barEvent);
return true;
}
threadSleep(); //blocks for 1 millisecond
++waitCount;
}
return false;
}
触发功能:通过设置触发周期的更新标志,触发一个事件达毫秒
bool trigger(uint8_t eventID, int timeout)
int waitCount = 0;
while(waitCount <= timeout)
{
setUpdateFlag(eventID, true); //Sets the update flag to true
if(globalEventID == eventID)
{
pthread_barrier_wait(&barEvent);
return true;
}
threadSleep(); //blocks for 1 millisecond
++waitCount;
}
setUpdateFlag(eventID, false);
return false;
}
我的问题是:是另一种与广播公司共享信息的方式,还是障碍真的是唯一有效的方式?此外,是否还有其他方法可以使用屏障获得超时功能?
基于您描述的问题:
具体来说,我试图让thread1知道它是等待已被线程2解析并存储在全局列表中,并且thread2可以继续解析和存储,因为thread1将现在从列表中复制该消息,确保thread2可以使用新版本覆盖该消息,并且不中断线程1的操作。
听起来您的问题可以通过让两个线程交替等待条件变量来解决。例如,在线程1:中
pthread_mutex_lock(&mutex);
while (!message_present)
pthread_cond_wait(&cond, &mutex);
copy_message();
message_present = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
process_message();
在线程2:中
parse_message();
pthread_mutex_lock(&mutex);
while (message_present)
pthread_cond_wait(&cond, &mutex);
store_message();
message_present = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
相关文章:
- 子线程中的条件变量等待停止主线程中的执行
- 正在连接的等待条件变量的线程会发生什么情况?
- 如何"stop"正在等待条件变量的分离线程?
- 如何修复条件变量等待/通知的竞争条件
- 可以在同一条件变量上等待多个线程
- 等待条件变量后未并行运行的线程
- 如何停止C 程序在等待条件时关闭时崩溃
- 等待条件变量是否会加载 CPU 内核
- 使用std::conditional_variable等待条件
- 你真的能用WaitFor..等待条件变量吗..对象
- C++如何等待条件满足
- 在发出等待条件变量的信号后,线程何时获取锁?是什么决定了它
- 为什么在使用qt等待条件时不必包装lock/unlock语句
- 等待条件的空循环(忙等待)
- Q等待条件,手动复位除外?(或者在Qt Concurrent之外创建QFuture对象?)
- 在1个线程上运行的boost::asio::io_service如何唤醒等待条件
- Boost:等待工作线程等待条件变量
- 如何在信号槽中设置等待条件
- 等待条件下的C++线程死锁
- 等待条件的非线程替代方案.(编辑:Proactor模式与boost.asio?)