pthread execution on linux

You are right in saying that the order of thread execution is not sequential. To some extent, that is the whole point of using threads, i.e. to run other tasks concurrently.

The output you are seeing is as expected, and can possibly be different.

Perhaps this will help:

   main            thread1     thread2
    |                
    |--create--------+-----------\
    |                |           |   
    |            "Thread 1"      |   "Thread 2" can
    |                |           |<- occur anywhere
    "https://stackoverflow.com/"   along this line
   join(1) ---------             |
    |                            |
    |                            |
  "amit"                         |
    |                            |
    |                            |
   join(2) ---------------------/
    |
    |
"Thread 1 returns"
"Thread 2 returns"
    |
  exit(0)

The only guarantee you have is:

  • Thread 1” will always be printed before “amit” (because pthread_join() waits for thread 1 to end before the main program can proceed)
  • Thread X returns ...” statements will always come at the end, after both threads have terminated.

Leave a Comment