多处理竞赛共享变量

时间:2017-09-19 14:49:26

标签: c unix operating-system

我正在做一个简单的生产者/消费者问题。我有一个生产者(厨师),当消费者(野蛮人)消耗所有这些食物时会生产部分食物,所以野蛮人必须等到厨师填满锅。我不明白我的错误是什么,因为野蛮人消费部分,但厨师没有填补空白。

这是该计划:

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <fcntl.h>

int shmid, semid;
int *portions;
sem_t *mutex, *empty, *full;

char sem_1[]= "mutex";
char sem_2[]= "full";
char sem_3[]= "empty";

void clear()
{

   if (shmctl(shmid,IPC_RMID,0) == -1) perror("shmctl");
}

void producer(int num, int m)   
{
  int i;

   while(1) { 


    }    
}

void consumer(int num, int rounds)   
{

       int i;



}


int main(int argc, char *argv[])
{

int i;
int N, M, NROUNDS, pid;


if (argc != 4)
{
    fprintf(stderr,"insert N savages, M portions e NROUNDS\n");
    exit(1);
}

N=atoi(argv[1]);
M=atoi(argv[2]);
NROUNDS=atoi(argv[3]);




/* generate producer and consumers */




      }

  for(i=0;i<N;i++) {
    pid=wait(NULL);
    printf("Terminate process %d\n", pid);
  }   

  clear();

}

这是输出:

./a.out 3 5 3

Savage[2] eats
Number of portions in pot: 4
Savage[1] eats
Number of portions in pot: 3
Savage[0] eats
Number of portions in pot: 2
Savage[2] eats
Number of portions in pot: 1
Savage[1] eats
Number of portions in pot: 0
Savage[0] eats
Number of portions in pot: -1
Savage[2] eats
Number of portions in pot: -2
Terminate process 10287
Savage[1] eats
Number of portions in pot: -3
Savage[0] eats
Number of portions in pot: -4
Terminate process 10285
Terminate process 10286

1 个答案:

答案 0 :(得分:1)

您的消费者使用互斥锁,表示存储器为空,然后永远不会释放互斥锁,这样,制作人就永远不会使用互斥锁并填充底池,并且您的进程将陷入僵局。

For a better understanding, read the Producer Consumer section in this great book.