When using loops (particularly in c++) do they all create their own threads? If not which loops create their own threads as opposed to which ones take control of execution of the main thread for the duration of their existence?
EDIT: What about the message loop which runs continuously, how come it’s existence in a program doesn’t prevent anything after the message loop from being executed since it’s a continuous loop?
Loops, such as
for-loops andwhile-loops never create threads. The main thread (or any other thread started somewhere in your code) can enter a loop, just like it can perform all other parts of your code, but a new thread will never be started as a result of entering a loop.There are special libraries that provide templates that can be used in a way similar to loops, e.g.
parallel_for. Those will be starting threads (or similar kinds of parallelism), but those are really function templates (or class templates), not loop statements as defined by the language standard.EDIT after comment:
In the specific example of a message loop you refer to in the comment below, the idea is that windows (which react to events coming from separate threads) and possibly various other threads are created before the main thread enters the loop. The loop then runs until a
WM_QUITmessage is received, causingGetMessageto return the equivalent of booleanfalse.So the loop runs in the main thread, but the messages it receives are generated by separate threads, created and started (either by the system or by you) before entering the loop.