How to wait for threads to finish their work, where threads created by clone in c?

后端 未结 1 499
轻奢々
轻奢々 2021-01-07 11:22

I try to wait the main function, till the threads finish their work. But the main function finish its work and exit. I think because of that the threads has not the correct

相关标签:
1条回答
  • 2021-01-07 12:19

    Per default a clone()ed process does not signal the parent about its end.

    If you want the parent to be signalled about the child's end you need to explicitly pass the signal to be sent on its end when clone()ing ORed to the 3rd parameter passed.

    If you use SIGCHLD then use waitpid() as usual.

    In this latter case clone and wait like so:

      thread_pid[i] = clone(incHelper, child_stack+STACK_SIZE, CLONE_VM | SIGCHLD, arg);
      pid_t pid = waitpid(thread_pid[i], &status, 0);
    

    If you want to use another signal to be sent on the child's end like for example SIGUSR1 you need to tell this to waitpid() using the option __WCLONE:

      thread_pid[i] = clone(incHelper, child_stack+STACK_SIZE, CLONE_VM | SIGUSR1, arg);
      pid_t pid = waitpid(thread_pid[i], &status, __WCLONE);
    

    This

    void* arg = (void*) &arguments;
    

    takes the address of arguments. As arguments already is an address of the required structure, it should be:

    void * arg = arguments;
    

    Note: As the main thread waitpid()s for the clone()ed thread to finish before the next call to clone(), there is no parallel processing of increment()

    0 讨论(0)
提交回复
热议问题