I am trying to understand pthreads by example. I have made the following code that is giving different answers everytime I run! Could anyone explain the bug please? TIA, Svi
There is no bug, this is just how threads work. Your main thread creates new threads, which are at that point "ready to run". At some point in time (determined by the OS), your main thread will be suspended and one of the other threads will run for a certain amount of time (usually a few tens of milliseconds). The system will keep switching between threads while there exist running threads for your program.
The exact point in time when your main thread will be interrupted and one of the other threads can print it's Hello World will depend on what the OS scheduler decides, based on how long your main thread is already running, other activity in the system, external (I/O) events, etc.
EDIT to include my comment below:
The reason why you're seeing 3, then 4, then only 2 "Hello Worlds", is that you created the threads, but you didn't wait for them to actually get scheduled and run. When your main loop ends, the program is dead, irrespective whether your other threads have had a chance to run. If you want all of your threads to be finished, you need to do a pthread_join
on each of your threads before returning from main.