gpt4 book ai didi

linux - C(linux平台)中基于事件的通信的最佳机制

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:58 31 4
gpt4 key购买 nike

我想在两个线程之间进行通信。只有一个事件会触发其他线程。

我的条件是基于事件的通信应该是高效的。我尝试使用消息队列,但通常 mq_send 需要时间。

最佳答案

我认为最好的方法是使用 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作为引用

关于linux - C(linux平台)中基于事件的通信的最佳机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27342982/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com