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

时间:2012-08-01 01:44:14

标签: c++ pthreads

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

我的问题:与广播公司分享信息的另一种方式,还是障碍真的是唯一有效的方式?另外,还有另一种获取超时功能的方法吗?

1 个答案:

答案 0 :(得分:2)

根据您描述的问题:

  

具体来说,我试图让thread1知道它的消息   等待已经被thread2解析并存储在全局列表中,   并且thread2可以继续解析和存储,因为thread1会   现在从列表中复制该消息,确保thread2可以   用新版本覆盖该消息而不破坏该消息   thread1的操作。

听起来你的问题可以通过让两个线程交替等待条件变量来解决。例如。在主题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);
相关问题