JeanYs JeanYs - 1 year ago 141
C Question

fork() to search through a 3D array C programming

I just learned about fork on the web, I understand the main principle with the child and parent processes but I am still a little bit confused on how we can use fork to search faster through a 3D array. Can anyone give a quick coded example to show how it works ?


Answer Source

Fork can make things run faster by allowing the calculations to be split up amongst the processors. Here's example code using a flat array (it's easier to get the concept across with a flat array instead of 3d array):

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);

In this example, the program splits into two processes and each process searches half of the array. I ran a the same program with 1000000000 elements in the array and these are the times:

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

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

I hope that helps, if I can clear anything else up let me know.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download