How to make main thread wait for all child threads finish?

c, multithreading

Solution

int main()
{
    pthread_t tid[2];
    for (int i = 0; i < 2; i++) {
        pthread_create(&tid[i], NULL, routine, NULL);
    }
    for (int i = 0; i < 2; i++)
       pthread_join(tid[i], NULL);
    return 0;
}

Problem

I intend to fire 2 threads in the main thread, and the main thread should wait till all the 2 child threads finish, this is how I do it. ``` void *routine(void *arg) { sleep(3); } int main() { for (int i = 0; i < 2; i++) { pthread_t tid; pthread_create(&tid, NULL, routine, NULL); pthread_join(&tid, NULL); //This function will block main thread, right? } } ``` In the above code, `pthread_join` indeed makes main thread wait for the child threads, but the problem is, the second thread won't be created untill the first one finishes. This is not what I want. What I want is, the 2 threads get created immediatly in the main thread, and then main thread waits for them to finish. Seems like `pthread_join` cannot do the trick, can it? I thought, maybe via a `semaphore` I can do the job, but any other way?

Original source