gpt4 book ai didi

c - C 条件变量中的 posix 线程

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

我已经完成了对条件变量的阅读,但我只是无法理解如何使用它们。

我有一棵树,截至目前,当你为一个已经存在的节点插入时,它返回 0,这意味着它已经存在因此失败。

我现在想扩展 pthreads 支持,而不是提到它不能完成,因为它已经存在并返回 0,我希望它在等待队列中,一旦请求的节点被删除,继续现在插入。

例如,

假设一棵树有3个节点,值为1、5、10如果我想插入一个值为 10 的新节点,而不是返回 0 并抛出该值已经存在的错误,它应该等待值为 10 的节点删除,一旦删除,它应该继续前进并插入。

我的 insert 函数 else block ,在它之前检查过该节点存在该值后返回 0,你可以放心,知道它存在的逻辑工作正常,现在我只是想添加条件变量支持它在哪里等待。数据字段条件在插入的第一行初始化,所以也完成了。我现在希望当它进入这个 block 时,cond_wait 是唯一将被执行的代码行,然后它将简单地等待直到删除信号。我的方法对吗?如果是,在删除中,我如何发出信号?请帮帮我,我花了几个小时阅读和查看示例,试图解决这个问题。

代码,

  else

{
//IF DUPLICATE EXISTS
pthread_mutex_lock(&m);
node->counter++;
pthread_cond_wait(&node->condition, &m);
_insert(string, strlen, ip4_address, node, NULL, NULL);
pthread_mutex_unlock(&m);

return 1;//I CHANGED IT FROM 0 to one, since if signalled, and if reached to this limit
//it was probably successful

}

最佳答案

这里是假设:

struct tree
{
... // some other data (whatever)
pthread_mutex_t mitex;
pthread_cond_t cond;
};

辅助函数:

int tree_contains_value(struct tree *t, int value)
{
return ...; // returns 0 or 1
}

这是一个插入:

void tree_insert(struct tree *t, int val)
{
pthread_mutex_lock(&t->mutex);
while (tree_contains_value(t, value))
{
pthread_cond_wait(&t->cond, &t->mutex);
}
... // do actual insert
pthread_mutex_unlock(&t->mutex);
}

和删除:

void tree_remove(struct tree *t, int val)
{
pthread_mutex_lock(&t->mutex);
... //remove value
pthread_cond_broadcast(&t->cond); // notify all wating threads if any
pthread_mutex_unlock(&t->mutex);
}

关于c - C 条件变量中的 posix 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981918/

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