gpt4 book ai didi

c - 生产者/消费者解决方案

转载 作者:行者123 更新时间:2023-11-30 21:08:51 26 4
gpt4 key购买 nike

我正在使用信号量实现生产者消费者问题的解决方案,并且到目前为止已经开发了这段代码,其中实现了生产者和消费者。

#define N 100               
typedef int semaphore;
semaphore mutex = 1;
semaphore empty = N;
semaphore full = 0;
void producer(void)
{
int item;
while (TRUE)
{
produce_item(&item);
down(&empty);
down(&mutex);
enter_item(item);
up(&mutex);
up(&full);
}
}
void consumer(void)
{
int item;
while (TRUE)
{
down(&full);
down(&mutex);
remove_item(&item);
up(&mutex);
up(&empty);
consume_item(item);
}
}

我正在努力思考如何实现每次生产/消费元素时打印数字的主程序。

如有任何帮助,我们将不胜感激

最佳答案

我建议在调用 enter_itemremove_item 后打印消息。这个问题最好使用线程来解决,但对于您的实现,请尝试生产“x”数量的项目(直到满),然后让消费者消费它们。

关于c - 生产者/消费者解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670558/

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