No errors, this is exactly how threads work. Your main thread creates new threads that are "ready to run" at this point. At some point in time (determined by the OS), your main thread will be suspended, and one of the other threads will work for a certain period of time (usually several tens of milliseconds). The system will continue switching between threads as long as there are current 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. Hello World will depend on what the OS scheduler decides, depending on how long your main thread has been running, other activity on the system, external (I / O) events, etc.
EDIT to include my comment below:
The reason you see 3, then 4, and then only 2 "Hello Worlds" is because you created the threads, but you didnβt wait until they really started planning and starting. When your main loop ends, the program is dead, regardless of whether your other threads had the ability to run. If you want all your threads to be finished, you need to do pthread_join
for each of your threads before returning from the main one.
source share