gpt4 book ai didi

c - 递归 C mergesort 在使用管道/叉读取时挂起

转载 作者:太空狗 更新时间:2023-10-29 15:36:20 26 4
gpt4 key购买 nike

我正在尝试使用递归 fork 系统创建一个包含 800 个整数的数组的合并排序,以便每个最底部的子级(总共 8 个)每个 qsort 100,然后将数组传回它们各自的父进程进行合并排序并再次向上传递。

由于某种原因,该函数在第一组最底层的子进程完成向其父进程的写入后挂起。

我的递归 fork 函数接收初始数组 800...

static void forkSort(int* parentNums, int size)
{
printf("PPid:%ld Pid:%ld Size:%d\n", (long)getppid(), (long)getpid(), size);
int childNums[size/2], fd[2], left, right;

if(size <= 100) //Send sorted array to parent thru pipe
{
qsort(parentNums, size, sizeof(int), compare);
write(fd[1], &parentNums, sizeof(parentNums));
exit(0);
}
if (pipe(fd)==-1){perror("Failed");}

size /= 2;
if(!(left = tryFork()) || !(right = tryFork())) //Children
{
if(left) copy(childNums, parentNums, size);
else copy(childNums, parentNums + size, size);

forkSort(childNums, size);
}
//Parents
int first[size], second[size], combined[size*2];
read(fd[0], first, sizeof(first));
read(fd[0], second, sizeof(second));

mergeSort(first, second, combined, size);
if(size*2 == SIZE) //Finished, write to out.dat
printArray(combined, SIZE);
else
write(fd[0], combined, sizeof(combined));
}

最佳答案

您的代码有几个问题(我必须补充一点,这看起来很有趣)。

A) 你应该 exit() 而不仅仅是返回客户端代码。否则你将继续执行,尤其是当你进行递归时。

B) 您需要将管道的写入端传递给您的客户,以便他们也知道在哪里写入。我将其作为参数添加到 forkSort()。

C) 当大小 <= 100 时,你执行 sizeof(parentNums) 这会变成 sizeof(int*),正确的方法是:大小(整数)*大小

D) 当你写回一组合并的整数时,你只写了第一部分,然后把它写到管道的读端。正确的调用是:write(write_fd, combined, sizeof(combined));

E) 我删除了 wait(NULL) 调用,因为我不明白这一点。同步将通过 read()write() 调用完成。

这是我的建议:

static void forkSort(int* parentNums, int size, int write_fd)
{
int fd[2];
printf("PPid:%ld Pid:%ld Size:%d\n", (long)getppid(), (long)getpid(), size);
int childNums[size/2], left, right;
if(size <= 100) //Send sorted array to parent thru pipe
{
qsort(parentNums, size, sizeof(int), compare);
write(write_fd, parentNums, size*sizeof(int));
exit(0);
}
if (pipe(fd)==-1){perror("Failed");}

printf("Creating child processes...\n");
size /= 2;

if(!(left = tryFork()) || !(right = tryFork())) //Children
{
if(left) copy(childNums, parentNums, size);
else copy(childNums, parentNums + size, size);
forkSort(childNums, size, fd[1]);
}

/* parent */
int first[size], second[size], combined[size*2];
read(fd[0], first, sizeof(first));
read(fd[0], second, sizeof(second));
printf("\n\nMerge sorting... Size:%d\n", size*2);
mergeSort(first, second, combined, size);
if(size*2 == SIZE) { //Finished, write to out.dat
printf("\nFinished!!! (%d)\n\n", size * 2);
printArray(combined, SIZE);
}
else {
write(write_fd, combined, sizeof(combined));
exit(0);
}
}

关于c - 递归 C mergesort 在使用管道/叉读取时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666261/

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