Search code examples
cmultithreadingpthreadssequential

I want to program in parallel in C, should i avoid to use pthread_join()?


i would like to create multiple threads and launch it at the same time they are created, for the code to goes the fastest possible i tried to do this :

for (i = 1; i < nbClients+1; i++)
{
    pthread_create(&tClient, NULL, procedureClient, &i);
    pthread_join(tClient, NULL);

    free(clients[i].panier); //Libération de la mémoire pour chaque panier
}

if i do pthread_join, the main thread is suspended so it's sequential, so if i do this :

for (i = 1; i < nbClients+1; i++)
{
    pthread_create(&tClient, NULL, procedureClient, &i);

    free(clients[i].panier); //Libération de la mémoire pour chaque panier
}

is this execution parallel ? is it normal if my printf are in a disorder ? (i think that this is normal but i prefer to ask)

Thanks


Solution

  • There are following issues.

    1. You need to have different pthread_t handles for different threads.
    2. Need different arg variables for different threads.
    3. You should call pthread_join() after creating all threads. pthread_join() will block the calling thread until the other thread exit. This will wait for that thread to exit.

    .

    pthread_t tClient[MAX_NUM_THREADS];
    int       arg[MAX_NUM_THREADS] = {0};
    
    for (i = 0; i < nbClients; i++)
    {
        arg[i] = i+1; //Changed your for loop.
        pthread_create(&(tClient[i]), NULL, procedureClient, (void*)&(arg[i]));
    }
    
    /* Other code. */
    
    for (i = 0; i < nbClients; i++)
    {
        pthread_join(tClient[i], NULL); //Will wait for ith thread to exit.
    
        free(clients[i].panier); //Libération de la mémoire pour chaque panier
    }
    

    is this execution parallel ? is it normal if my printf are in a disorder ? (i think that this is normal but i prefer to ask)

    Now the execution is parallel. Prints in different threads may come in different order. It depends on which thread gets scheduled at what time. You can synchronize the threads using mutex, semaphores, condition variables. etc.