abbas_ali123
abbas_ali123

Reputation: 55

pthread programming, threads don't run simultaneously

I've the following code in my programm:

for (i = 0; i < numthrs; i++)
{


    if (0 != pthread_create(&thrs[i], NULL, thr_main,
                &args[i]))
    {
        /* handle error */
    }

    printf("thread %d created.\n", i);

    if (0 != pthread_join(thrs[i], &thread_status))
    {
        /* handle error */
    }

    printf("joined thread %d\n", i);
}

But I've noticed that the threads don't run simultaneously, the second thread starts its execution only after the first thread has completed its execution. I'm new to pthread programming. Can someone tell me what's the proper way to start some threads simultaneously?

Upvotes: 2

Views: 1913

Answers (1)

abligh
abligh

Reputation: 25119

This is because you pthread_join each thread immediately after creating it, i.e. you are waiting for thread n to complete prior to starting thread n+1.

Instead, try:

for (i = 0; i < numthrs; i++)
{
    if (0 != pthread_create(&thrs[i], NULL, thr_main,
                &args[i]))
    {
        /* handle error */
    }

    printf("thread %d created.\n", i);
}

for (i = 0; i < numthrs; i++)
{
    if (0 != pthread_join(thrs[i], &thread_status))
    {
        /* handle error */
    }

    printf("joined thread %d\n", i);
}

Upvotes: 2

Related Questions