我必须编写一个c程序(linux)来在数组中搜索最大值,同时使用10个子项。数组大小为1000.每个孩子从100个数字中搜索最大值。父母应该在管道上获得结果。我的代码不完美。主要问题是管道。父母只获得第一个最大值。第二个问题是,孩子们没有在同一时间运行(不是一个大问题,但可能有人可以告诉我什么是错) 我为我的代码做了一些笔记,但我的英语是如此糟糕的sry。 我希望我以正确的形式复制源代码。使用叉子和管道在数组中搜索最大值
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int array[1000]; //main array
int i;
srand (time(NULL)); //for not the same numbers
for(i=0;i<1000;i++){ //array upload
array[i]= (rand() % (10000+1)); //from 1 to 10000 random numbers
}
int searchminindex; //search index, 0-100,100-200, etc
int searchmaxindex;
int threads = 10; //number of threads
int fd[2];
pipe(fd);
int arraymax[10]; //the 10 max numbers
for(i=0;i<threads;i++){ //for 10 threads
if(fork() == 0){
close(fd[0]); //close reading
searchminindex=i*100; //number of thread * arraysize/threadsnumber
searchmaxindex=(i+1)*100;
int maxindex=searchminindex; //it will store the max number index, start from the search min index
int j;
for(j=searchminindex;j<searchmaxindex;j++){ //max search
if(array[maxindex]<array[j]){
maxindex=j;
}
}
write(fd[1], &array[maxindex], sizeof(array[maxindex])); //write the max number into the pipe
printf("max: %d\n", array[maxindex]); //that for check the result, will be deleted from the final code
close(fd[1]); //close write
wait(NULL);
exit(0);
}
else{
wait(NULL);
close(fd[1]); //close write
read(fd[0], &arraymax[i], sizeof(arraymax[i])); //read the max and store in arraymax[]
close(fd[0]); //close read
printf("the read max from the pipe: %d\n", arraymax[i]); //that for check the result, will be deleted from the final code
}
}
int arraymaxi=0; //it is search the max in the main array for check the result, will be deleted
int k;
for(k=0;k<1000;k++){
if(array[arraymaxi]<array[k]){
arraymaxi=k;
}
}
printf("maxi: %d\n", array[arraymaxi]); //end of checking the correct result, will be deleted
int l; //check the max numbers from the forks, will be deleted
for(l=0;l<10;l++){
printf("from the pipe max: %d\n", arraymax[l]);
}
int h; //search the true max from the 10 numbers
int truemaxindex=0;
for(h=0;h<10;h++){
if(arraymax[truemaxindex]<arraymax[h]){
truemaxindex=h;
}
}
printf("the final max: %d\n", arraymax[truemaxindex]);
return 0;
谢谢!我彻底关闭并等待,现在它完美地工作!所有的孩子在同一时间运行,父母得到所有结果。但是,我可以在哪里关闭读写?第一次后?或没有必要关闭? – AsdFork
@AsdFork如果不需要,您应该关闭管端。如果你考虑它,*两个*端必须在fork循环期间保持打开状态,因为每个子进程都需要写入端,并且父进程最终需要读取端。顺便说一句,你的代码的一个简单的改编,也解决了你的并发问题[可以在这里看到](http://pastebin.com/zUnUPGPN)。祝你好运。 – WhozCraig