Multiple fork() Concurrency

前端 未结 4 1485
花落未央
花落未央 2020-12-29 00:19

How do you use the fork() command in such a way that you can spawn 10 processes and have them do a small task concurrently.

Concurrent is the operative word, many pl

相关标签:
4条回答
  • 2020-12-29 00:29

    Just loop in the "main" process spawning one child after another with each assign a particular task.

    0 讨论(0)
  • 2020-12-29 00:31

    You might also want to look into POSIX Threads (or pthreads). Here is a tutorial:

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

    0 讨论(0)
  • 2020-12-29 00:34

    When you fork off processes the WILL be running concurrently. But note that unless you have enough available idle processors, they might not actually be executing concurrently, which shouldn't really matter...

    Your second paragraph makes it seem like you aren't understanding how fork works, you have to check the return code to see if you are in the parent or in the forked process. So you would have the parent run a loop to fork off 10 processes, and in the children you do whatever you wanted to do concurrently.

    0 讨论(0)
  • 2020-12-29 00:47

    Call fork() in a loop:

    Adding code to wait for children per comments:

    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);
    
    0 讨论(0)
提交回复
热议问题