gpt4 book ai didi

c - 共享变量的多处理竞赛

转载 作者:行者123 更新时间:2023-11-30 20:20:26 25 4
gpt4 key购买 nike

我正在做一个简单的生产者/消费者问题。我有一个生产者(厨师),当消费者(野蛮人)消耗完所有部分时,他会生产部分,因此野蛮人必须等到厨师将锅填满。我不明白我的错误是什么,因为野蛮人吃掉了一部分,但厨师却没有填满锅。

这是程序:

#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

最佳答案

你的消费者获取互斥锁,发出信号表明锅是空的,然后永远不会释放互斥锁,这样,生产者就永远无法获取互斥锁并填充锅,你的进程将陷入僵局。

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

关于c - 共享变量的多处理竞赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46303547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com