fork()通过3D数组C编程进行搜索

时间:2016-08-12 19:56:35

标签: c multidimensional-array fork

我刚学会了关于网络上的fork,我理解了子进程和父进程的主要原理,但我仍然对如何使用fork更快地通过3D数组进行搜索感到困惑。任何人都可以给出一个快速编码的例子来说明它是如何工作的吗?

谢谢

2 个答案:

答案 0 :(得分:3)

我建议你查看posix线程。不同之处在于线程在同一个进程中工作,因此它们共享地址空间(因为在线程之间然后在进程之间交换数据更快更容易)。为了更快地搜索,你应该将N维数组划分为X个组(较小的数组 - 每个线程/进程一个),并将每组N维数据传递给特定的线程(pthread)/ process(fork)。

答案 1 :(得分:3)

Fork允许在处理器之间拆分计算,从而使事情运行得更快。这是使用平面数组的示例代码(使用平面数组而不是3d数组更容易获得概念):

int main() {
    int i;
    int array[] = {0,1,2,3,4,5,6,7,8,9,10};
    int findThisNumber = 8;
    int pid = fork(); //split into two processes
                      //the parent return the childs pid
                      //and the child returns 0

    if(pid == 0) { //this is the child
        for(i = 0; i < 5; i++) { //scan the first half of the array
            if(array[i] == findThisNumber) {
                printf("%d found at index %d\n", findThisNumber, i);
            }
        }
    } else { //this is the parent
        for(i = 6; i < 10; i++) { //scan the second half
            if(array[i] == findThisNumber) {
                printf("%d found at index %d\n", findThisNumber, i);
            }
        }
    }
}

在此示例中,程序分为两个进程,每个进程搜索一半数组。我在阵列中运行了一个包含1000000000个元素的相同程序,这些是时间:

time ./noFork.exe
real    0m0.796s

time ./a.exe
real    0m0.391s

我希望有帮助,如果我能清除其他任何事情,请告诉我。