Multiple Forks () Concurrency

How do you use the fork () command so that you can create 10 processes and perform their small task at the same time.

Concurrent is a quick word, in many places that show how to use fork, use only one fork () call in your demos. I thought you would use some kind of loop cycle, but I tried, and it seems in my tests that fork () spawns a new process, does the work, and then spawns a new process. So they seem to work sequentially, but how can I use fork at the same time and have 10 processes doing work at the same time, if that makes sense?

Thanks.

Update: Thanks for the answers guys, I just misunderstood some aspects of fork (), but I understand it now. Greetings.

+6
c command-line unix concurrency multiprocessing
source share
4 answers

Call fork() in a loop:

Adding code to wait for comments for children:

 int numberOfChildren = 10; pid_t *childPids = NULL; pid_t p; /* Allocate array of child PIDs: error handling omitted for brevity */ childPids = malloc(numberOfChildren * sizeof(pid_t)); /* Start up children */ for (int ii = 0; ii < numberOfChildren; ++ii) { if ((p = fork()) == 0) { // Child process: do your work here exit(0); } else { childPids[ii] = p; } } /* Wait for children to exit */ int stillWaiting; do { stillWaiting = 0; for (int ii = 0; ii < numberOfChildren; ++ii) { if (childPids[ii] > 0) { if (waitpid(childPids[ii], NULL, WNOHANG) != 0) { /* Child is done */ childPids[ii] = 0; } else { /* Still waiting on this child */ stillWaiting = 1; } } /* Give up timeslice and prevent hard loop: this may not work on all flavors of Unix */ sleep(0); } } while (stillWaiting); /* Cleanup */ free(childPids); 
+15
source share

When you roll back processes, WILL will be executed at the same time. But keep in mind that if you do not have enough available inactivity processors, they may not run at the same time, which does not really matter ...

Your second paragraph says that you don’t understand how the plug works, you need to check the return code to see if you are in a parent or forked process. Thus, you will have a parent cycle to deploy 10 processes, and in children you do everything you want to do at the same time.

+4
source share

Just a cycle in the "main" process, generating one child after another, each of which assigns a specific task.

+3
source share

You can also look into POSIX threads (or pthreads). Here is a tutorial:

https://computing.llnl.gov/tutorials/pthreads/

0
source share

All Articles