gpt4 book ai didi

c - 如何避免在 pthreads 中进行轮询

转载 作者:太空狗 更新时间:2023-10-29 15:18:29 25 4
gpt4 key购买 nike

我有一些代码目前看起来像这样(简化)

/* instance in global var *mystruct, count initialized to 0 */
typedef struct {
volatile unsigned int count;
} mystruct_t;

pthread_mutex_t mymutex; // is initialized

/* one thread, goal: block while mystruct->count == 0 */
void x(void *n) {
while(1) {
pthread_mutex_lock(&mymutex);
if(mystruct->count != 0) break;
pthread_mutex_unlock(&mymutex);
}
pthread_mutex_unlock(&mymutex);
printf("count no longer equals zero");
pthread_exit((void*) 0)
}

/* another thread */
void y(void *n) {
sleep(10);
pthread_mutex_lock(&mymutex);
mystruct->count = 10;
pthread_mutex_unlock(&mymutex);
}

这对我来说似乎是低效和错误的——但我不知道更好的方法。有没有更好的方法,如果有,是什么?

最佳答案

条件变量允许您等待某个事件,并有一个不同的线程信号通知该条件变量。

您可以有一个执行此操作的线程:

for (;;)
{
if (avail() > 0)
do_work();
else
pthread_cond_wait();
}

和执行此操作的不同线程:

for (;;)
{
put_work();
pthread_cond_signal();
}

当然非常简单。 :) 您需要了解如何正确使用它,由于竞争条件,使用条件变量存在一些困难。

但是,如果您确定线程将阻塞很短的时间(以微秒为单位)并且很少阻塞,那么使用这样的自旋循环可能会更有效。

关于c - 如何避免在 pthreads 中进行轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6243451/

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