轮子。主流程 (A) 将创建一个子流程 (B),该子流程将创建另一个子流程 (C)。 然后主进程(A)将生成一个随机数(1000到2000之间)发送给进程B。 进程 B 将减去 10 个单位,并将该数字发送给进程 C。C 将减去 20 个单位,并将 将数字发送给 A。A 进程将减去 30 个单位,然后再次将数字发送给 B。等等, 直到值小于零。这一刻游戏将停止。胜利者是建立的过程 负数。
所有进程之间的通信都是通过管道 channel 完成的。
我的解决方案是:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
int pass(char* id, int in, int out, int x)
{
int n;
read(in, &n, sizeof(int));
printf("%s %d\n", id, n);
n=n-x;
printf("x= %d\n", x);
write(out, &n, sizeof(int));
return n;
}
void closeall(int* a, int* b, int* c)
{
close(a[0]);
close(a[1]);
close(b[0]);
close(b[1]);
close(c[0]);
close(c[1]);
}
int main()
{
int a2b[2], b2c[2], c2a[2], n, x;
pipe(a2b);
pipe(b2c);
pipe(c2a);
srand(time(NULL));
n=rand() % 1001 + 1000;
x=0;
write(c2a[1], &n, sizeof(int));
if (fork() == 0){
while (pass("grandfather ", c2a[0], a2b[1], x) > 0){
x=x+10;}
exit(0);
}
if (fork() == 0){
while (pass("father ", a2b[0], b2c[1], x) > 0){
x=x+10;}
exit(0);
}
if (fork() == 0){
while (pass("child ", b2c[0], c2a[1], x) > 0){
x=x+10;}
exit(0);
}
closeall(a2b, b2c,c2a);
wait(0);
wait(0);
wait(0);
return 0;
}
运行程序后结果是
grandfather 1420
x= 0
father 1420
x= 0
child 1420
x= 0
grandfather 1420
x= 10
father 1410
x= 10
child 1400
x= 10
grandfather 1390
x= 20
father 1370
x= 20
child 1350
x= 20
grandfather 1330
x= 30
father 1300
x= 30
child 1270
x= 30
grandfather 1240
x= 40
father 1200
x= 40
child 1160
x= 40
grandfather 1120
x= 50
father 1070
x= 50
child 1020
x= 50
grandfather 970
x= 60
father 910
x= 60
child 850
x= 60
grandfather 790
x= 70
father 720
x= 70
child 650
x= 70
grandfather 580
x= 80
father 500
x= 80
child 420
x= 80
grandfather 340
x= 90
father 250
x= 90
child 160
x= 90
grandfather 70
x= 100
father -30
x= 100
child -130
x= 100
有人可以帮助我改进源代码以获得正确的结果吗?如前所述,x 的减值三次相同,并且在第一个负数之后不会停止。
最佳答案
在您的程序中,多线程根本没有任何意义,因为每个线程都必须等待直到获得下一个值,或者正在计算,因为每个线程都需要前一个线程的结果。这意味着总是有两个线程在等待,一个正在运行。
这也是你程序的问题。这些线程异步运行,不会等待前一个线程完成其计算。
关于Ubuntu 下的 C - 尝试解决 "Wheel game"时未出现预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718830/