【发布时间】:2012-11-14 20:51:47
【问题描述】:
我的代码在这里:http://pastebin.com/Fi3h0E0P
这是输出
0
Should we take order today (y or n): y
Enter order number: 100
More customers (y or n): n
Stop serving customers right now. Passing orders to cooker:
There are total of 1 order(s)
1
Roger, waiter. I am processing order #100
目标是服务员必须接受订单,然后将它们交给厨师。服务员必须等待厨师完成所有比萨饼,送出比萨饼,然后接受新订单。
我在之前的帖子here 中询问了 P-V 的工作原理。
我认为这与\n 消费无关?我尝试了wait() 的各种组合,但都不起作用。
我在哪里做错了?
主要部分在这里:
//Producer process
if(pid > 0)
{
while(1)
{
printf("0");
P(emptyShelf); // waiter as P finds no items on shelf;
P(mutex); // has permission to use the shelf
waiter_as_producer();
V(mutex); // cooker now can use the shelf
V(orderOnShelf); // cooker now can pickup orders
wait();
printf("2");
P(pizzaOnShelf);
P(mutex);
waiter_as_consumer();
V(mutex);
V(emptyShelf);
printf("3 ");
}
}
if(pid == 0)
{
while(1)
{
printf("1");
P(orderOnShelf); // make sure there is an order on shelf
P(mutex); //permission to work
cooker_as_consumer(); // take order and put pizza on shelf
printf("return from cooker");
V(mutex); //release permission
printf("just released perm");
V(pizzaOnShelf); // pizza is now on shelf
printf("after");
wait();
printf("4");
}
}
所以我想这是执行路径: 进入waiter_as_producer,然后进入子进程(cooker),然后将控制权交还给父进程,完成waiter_as_consumer,切换回子进程。这两个等待切换回父级(就像我说我尝试了所有可能的 wait() 组合......)。
【问题讨论】:
-
各个进程阻塞了哪些等待操作?
-
另外,
wait()是做什么的?如果它是 POSIX 函数,那么它应该是没有必要的 -P()并且也许V()应该等待。 -
这是头文件pastebin.com/4Jse4bRg,最后定义了P,V。
-
添加一些 \n 到 printf 字符串。标准输出是行缓冲的。
-
@User007 这是对我有用的要点:gist.github.com/4075391
标签: c algorithm unix semaphore producer-consumer