-1

I am new to multi threading and am following "Advanced programming in unix environment". I am not able to get the order in which the threads are executed. I have the following code.

int err1 = pthread_create(&first, NULL, disp, a);
int err2 = pthread_create(&second, NULL, disp, b);
int err3 = pthread_create(&third, NULL, disp, c);

But the thread related to third tid is executing first, then the second and finally the first. Not sure if this is the behavior or something going wrong.

Thx! Rahul.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
rahul
  • 6,447
  • 3
  • 31
  • 42
  • 2
    The primary point of threads is to run in parallel, which means there's no ordering relationship between them. If you want ordering in a *few* places, you generally use synchronization to do that. If you want the processes to be sequential in general (e.g., `second` can't run at all until `first` finishes) just run them in the same thread. – Jerry Coffin Oct 03 '12 at 15:09
  • 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:52

3 Answers3

3

It's not deterministic. Threads run in parallel, so it will depend on how many processors and hyperthreading you have. If you want them in a given order, you need to use synchronisation points. Once started all threads run independently at their own rate.

Julian
  • 852
  • 4
  • 9
2

There is no guarantee about the order of executing the code once they are created.
Only thing that can be guaranteed is that Thread 3 will be created after Thread 2 and Thread 2 will be created after Thread 1.
You cannot predict or assume that thread 2 will be spawned only after certain code has executed in thread 1. If you want to achieve something like that you need to provide your some Thread synchronization.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Your program is running in one thread, and creates a further three. All you can guarantee, is the order the three other threads are created and that they will be executed at some stage. The OS could stop your main thread, and complete the new threads for you in order as they are created, it could stick them in some of stack of thread to look at later once your main program has finished creating them. The key point is, you really do not know.

If you need these three threads to be executed in order and to complete before the next one starts, you basically need to not to use threads in the first place.

thecoshman
  • 8,394
  • 8
  • 55
  • 77