我想在这两个线程之间进行通信。只有一个事件会触发其他线程。
我的条件是基于事件的通信应该是有效的。我尝试使用消息队列,但通常mq_send很耗时。
发布于 2014-12-07 22:22:03
我认为最好的方法是使用Pthread_mutex和pthread_cond
您应该等待事件,如下所示:
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_mutex_lock(&>lock);
/* releasing the mutex and block untill a cond get a signal*/
pthread_cond_wait(&cond, &lock);
/* execute your code */
your_condtion = 0;
/* signaling the producer that we "consumed" the data */
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);您应该按如下方式发送事件:
/* checking if consumer already used our data */
pthread_mutex_lock(&lock);
while(your_condition != 0)
pthread_cond_wait(&cond, &lock);
/* execute your code */
your_condition = 1;
/* sending event */
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);您可以使用my producer consumer example作为参考
https://stackoverflow.com/questions/27342982
复制相似问题