2

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.