C 共享变量的多进程竞争
我正在做一个简单的生产者/消费者问题。我有一个制作人(厨师),当消费者(野蛮人)吃掉所有的食物时,他会生产食物,所以野蛮人必须等到厨师把锅装满。我不明白我的错误是什么,因为野蛮人会吃一份,但厨师不会把锅装满 以下是节目:C 共享变量的多进程竞争,c,unix,operating-system,C,Unix,Operating System,我正在做一个简单的生产者/消费者问题。我有一个制作人(厨师),当消费者(野蛮人)吃掉所有的食物时,他会生产食物,所以野蛮人必须等到厨师把锅装满。我不明白我的错误是什么,因为野蛮人会吃一份,但厨师不会把锅装满 以下是节目: #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <sys/types.h> #include <unistd.h> #inc
#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();
}
您的使用者接收互斥锁,发出信号,表示容器为空,然后再也不会释放互斥锁,这样,生产者就永远不能接收互斥锁并填充容器,您的进程将死锁
如果我用这个来更改它,程序不会启动:If((*部分)==0){sem_post(互斥)sem_post(空)SimiAuto(FULL)阅读我链接的书,你的算法可能有超过1个问题。你确定信号量是正确的同步机制吗?考虑条件变量…
./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