c - 为什么我的生产者消费者阻塞了?

标签 c algorithm unix semaphore producer-consumer

我的代码在这里: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

目标是服务员必须接受订单,然后将订单交给厨师。服务员必须等待厨师完成所有披萨、送出披萨,然后接受新订单。

我在之前的帖子中问过 P-V 是如何工作的 here .

我觉得跟\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),然后将控制权交回parent,完成waiter_as_consumer,切换回child。这两个等待切换回父级(就像我说的我尝试了所有可能的 wait() 组合...)。

最佳答案

  • 改为#define PERMS (0) (它不是八进制文件模式掩码!)
  • 删除所有wait();小号
  • 按 sizeof 缩放大小:if((shmid=shmget(1000,sizeof (int) * BUFSIZE,IPC_CREAT | PERMS)) < 0) , 和其他(大小以 semsize/pagesize 为模放大,但无论如何使用正确的大小是一个好习惯)

解决了这里的问题。

整个想法是:您不需要等待; {producer,consumer} 之一将在某处的 P() 上被阻塞:

来自 P():

sb.sem_flg = 0; /* blocking call */
    if (semop(sid, &sb, 1) == -1)
        perror("semop");

此外:wait(&status)至少需要一个论点。 (您可能需要其他等待函数之一,例如 wait3() 或 waitpid() )

除此之外:

  • 我会在共享对象的声明之前加上“volatile”:volatile int *buff;
  • main() 应该返回 int,没有值的返回是错误的(c99 之前)
  • 大多数指针操作都很笨拙:order = buffer[i];order = *(buffer+i);相同, 但更具可读性。

关于c - 为什么我的生产者消费者阻塞了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13387098/

相关文章:

java - 类似于 Soundex、Metaphone 等功能的数值转换算法

algorithm - 枚举前 2^20 条不包括两个顶点之间的循环的路径

linux - 将位于两个字符之间的文件内容分隔成单独的文件

java 类路径 unix

c - 读取图像文件内容到缓冲区

algorithm - 这是NP问题吗?

C 成语和鲜为人知的事实

C 套接字程序作为 Web 服务器在云端运行,不接收浏览器的任何响应

c - 使用 scanf 读取除换行符之外没有其他内容的整数

c++ - a.out linux 可执行文件属于哪个程序?