我正在使用信号量实现生产者消费者问题的解决方案,并且到目前为止已经开发了这段代码,其中实现了生产者和消费者。
#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_item
和 remove_item
后打印消息。这个问题最好使用线程来解决,但对于您的实现,请尝试生产“x”数量的项目(直到满),然后让消费者消费它们。
关于c - 生产者/消费者解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670558/