Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthreads and concurrency

I have the following code:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define LOOPS 10000

void *run(void *arg)
{
    int id = strtol(arg,NULL,0);
    int i;
    for(i=0; i<LOOPS; i++)
    {
        printf("In %d.\n",id);
    }
}

int main()
{
    pthread_t p1,p2;
    void *res;

    pthread_create(&p1,NULL,run,"1");
    pthread_create(&p2,NULL,run,"2");
    pthread_join(p1,&res);
    pthread_join(p2,&res);
    return 0;
}

When I run this, either the string "In 1" displays 10000 times consecutively then "In 2" displays 10000 times consecutively or vice versa. Shouldn't the strings be alternating and not displaying consecutively as they are here?

like image 471
lbj-ub Avatar asked Feb 27 '26 21:02

lbj-ub


1 Answers

The order in which threads are interleaved by the scheduler is not deterministic (...well it is but only from the scheduler's/kernel's point of view). You should not make assumptions about the order.

In this situation you experience that either one of the threads is allowed to complete their whole work before the scheduler ->preempts it and allows the other thread to run.

like image 67
Bernd Elkemann Avatar answered Mar 02 '26 05:03

Bernd Elkemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!