0

I have a basic program to test pthread_create:

int main (int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];
    long t;

    for(t=0; t<NUM_THREADS; t++){

        /* TODO assignment 3.2 a) */
        pthread_create(&threads[t], NULL, SomeFunction, t);
//      pthread_join(threads[t], NULL);

    }

    printf("Completed. Exiting\n");
    pthread_exit(NULL);
}

Everytime I ran it, it creates threads in a random order without considering the for loop. What is the reason for that?

www
  • 586
  • 1
  • 14
  • 29
  • Possible duplicate of [pthread execution on linux](https://stackoverflow.com/questions/4991470/pthread-execution-on-linux), [Pthread Run a thread right after it's creation](https://stackoverflow.com/q/12536649/608639), etc. – jww Aug 14 '19 at 12:55

1 Answers1

2

I assume what you mean is that you're seeing the results of (or some side-effect of) SomeFunction occurring not strictly in ascending order of t.

A thread, by definition, is a unit of asynchronous execution, whose state (executing or not) is determined by the OS. The OS is free to schedule threads as it sees fit. Other than by virtue of not existing and then existing, the order in which you happen to create those threads is not an "input" to the OS's scheduler. If you need things in different threads to happen in a specific order, you have to manually synchronize those threads using synchronization primitives like semaphores, mutexes, etc.

In short, this is just "the way threading works." I would expect the order in which you saw results/side-effects of threads created this way to be effectively non-deterministic with respect to t.

ipmcc
  • 29,581
  • 5
  • 84
  • 147