C 如何使子进程交替访问和更改相同的值
这是我的节目:C 如何使子进程交替访问和更改相同的值,c,multiprocessing,fork,pipe,C,Multiprocessing,Fork,Pipe,这是我的节目: int a; int main(void) { a=10; //declare and create 2 pipes int p1[2], p2[2]; pipe(p1); pipe(p2); int ra; for(int i=0;i<3;i++) { pid=fork(); if(pid==0) { close(p1[1]); close(p2[0]); read(p1[0],&ra,3);
int a;
int main(void)
{
a=10;
//declare and create 2 pipes
int p1[2], p2[2];
pipe(p1);
pipe(p2);
int ra;
for(int i=0;i<3;i++)
{
pid=fork();
if(pid==0)
{
close(p1[1]);
close(p2[0]);
read(p1[0],&ra,3);
while(ra>0)
{
ra-=1;
printf("%i a are available, reported by process %i\n",ra,getpid());
close(p1[0]);
write(p2[1],&ra,3);
close(p2[1]);
}
break;
}
else
if(pid>0)
{
}else
{
wait(NULL);
}
}
}
if(pid>0) //parent process outside for loop
{
close(p1[0]);
close(p2[1]);
if(a>0)
{
write(p1[1],&a,3);
close(p1[1]);
}
else
exit(0);
read(p2[0],&ra,3);
a=ra;
close(p2[0]);
}
但实际产出是:
35 seats are available, reported by process 2
34 seats are available, reported by process 2
33 seats are available, reported by process 2
32 seats are available, reported by process 2
31 seats are available, reported by process 2
....
1 seats are available, reported by process 2
0 seats are available, reported by process 2
问题:我不知道如何强制其他子进程交替(或随机)运行,因此结果与上面的第一个类似。
请帮助我。如果您关心工作完成的顺序,那么您必须编写代码来强制执行特定的顺序。否则,实现可以自由选择最有效的顺序。您可以使用互斥锁、sempahore、管道、文件或任何其他您喜欢的同步机制,但您必须真正做到这一点。它不会自行发生
如果
fork
返回错误,为什么要调用wait
?while循环中的出现了严重错误。每次在循环中,您都会写入并关闭,p2[1]
。@DavidSchwartz如果我错了,您能具体说明一下吗?您所说的“您两个都向写入”是什么意思?每次在的循环中,您向p2[1]
写入并关闭p2[1]
。这不可能是对的,因为这意味着你不止一次地关闭同一个东西,然后在关闭后再写。仔细查看您的,而循环。Schewartz我不需要它来订购。我希望其他子进程有机会访问和更改该值。@TungPham他们有机会访问和更改该值。所以你有你想要的。(他们没有利用这个机会,因为这是低效的。如果你想要一些低效的东西,你必须强迫它。)我的意思是,如何让第一个进程放弃CPU,这样其他人也可以进入并更改值。这就像pthread中的pthread_yield,但我不想使用pthread。简而言之,我希望输出与上面的第一个输出一样。@TungPham如果您的平台支持,您可以使用sched_yield
。(如果不是,你的平台可能有一些等价物。)这将鼓励系统效率降低,并切换进程,即使这是浪费并导致性能低下。我认为shced_yeild只适用于线程,而不是进程。
35 seats are available, reported by process 2
34 seats are available, reported by process 2
33 seats are available, reported by process 2
32 seats are available, reported by process 2
31 seats are available, reported by process 2
....
1 seats are available, reported by process 2
0 seats are available, reported by process 2