什么时候使用pthread屏障而不是条件等待和广播更合适

When is it more appropriate to use a pthread barrier instead of a condition wait and broadcast?

本文关键字:等待 条件 广播 pthread 什么时候      更新时间:2023-10-16

我正在用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);