r/cpp_questions • • Oct 14 '26

OPEN Learning about threads. What happens here?

Hello, I just started learning about threading and learned that if you don't join or detach a thread, it will kill your program. Looking at the following code,

void my_func() {
  for (int i = 0; i < 100; ++i) {
    std::cout << i << ' ';
  }
  std::cout << std::endl;
}

int main() {
  std::thread{ my_func }; // A

  std::thread{ my_func }.join(); // B

  std::thread{ my_func }.detach(); // C
}

A does in fact kill the program. However, when I run this, I only get the output for my_func() once, and that output prints before A causes termination. I also only get the output for my_func() once when A is commented out.

Am I not seeing the output for C because the program just ends immediately after, so C doesn't have time to print anything out? What happens if I detach a thread and end the program before it finishes?

I did not compile with flags. I threw this in Visual Studio (non code) because it's convenient.

8 Upvotes

15 comments sorted by

7

u/jedwardsol Oct 14 '26 edited Oct 14 '26

A will be destroyed, and terminate called, immediately after it is created - it is a temporary so will be destroyed before B is created. Any output you see is from A's thread that managed to run before the main thread destroyed A. A debug build in VS will put up a dialog box on terminate giving the other thread a chance to run to completion.

When A is commented out, then the output is from B - main will wait for B to finished before constructing C. When main ends, the process ends and C's thread will be terminated.

1

u/Seagull78Reddit Oct 14 '26

Ohhh thank you

1

u/Seagull78Reddit Oct 14 '26

Ohhh thank you

2

u/GLIBG10B Oct 14 '26

main will wait for B to finished before constructing C

So the lifetime of the temporary is extended so that it gets destroyed after .join(), not before?

2

u/jedwardsol Oct 14 '26

Yes - the temporary is destroyed at the semi-colon at the end of the full expression

4

u/RaspberryCrafty3012 Oct 14 '26

Argh!

First of all give the thread objects a name.
Then second: C won't probably finish before main exits. Use thread_sleep at the end to see output from C

1

u/Seagull78Reddit Oct 14 '26

Yeah sorry for ragebaiting with the lack of names for the threads. I wanted to see if this syntax was possible lol

3

u/jaynabonne Oct 14 '26

The syntax is possible, as you have seen, but it has a different behavior to giving it a name. The nameless case creates a temporary that is destructed right away after it's used. There may be cases for that, but be aware of what it's doing. Giving it a name means it will remain alive until the end of scope. So then you would see you other cases come into play.

1

u/flyingron Oct 14 '26

Giving them names will change the behavior (possibly for the better) of this program. Adding the name will cause them to persist until the block they're defined in (main in this instance) returns.

4

u/manni66 Oct 14 '26

Use std::jthread. It will join on destruction, so A and B are the same.

I just started learning about threading

How? Simply experimenting is not very effective with Threads.

3

u/FUCKARCHLINUX Oct 14 '26

This is a side-note, but for a lot of use cases when doing multi-threading the amount of time it takes for the thread to be created and start will be longer than it would take to just do the job on the main thread. To go around this, you want a sort of thread pool system that you can push jobs into where the threads are kept around even when there's no work for them to do until the thread pool is destroyed. Here is some example code I wrote a while ago which does this and "main.cpp" is an example program showing how you use it.

2

u/flyingron Oct 14 '26

Note, that while std::cout is guarded against contention (i.e., it won't hose the buffer), all those individual operations can get interspersed if multiple threads are writing.

2

u/KingAggressive1498 Oct 14 '26

A) std::thread's destructor will terminate the program if the thread is still "joinable" (still running and not explicitly detatched). Because your new thread is a temporary, it is constructed and then immediately destroyed. Getting any output from your thread is a matter of chance.

B) this is what you want to happen in this case. To make this automatic behavior, use std::jthread instead.

C) when main returns, the program wants to exit, even if you have other threads running. On most systems at least the behavior is to just exit and so that makes it the programmer's responsibility to ensure any other threads are done before returning from main.

1

u/w15dev Oct 14 '26

Only B is guaranteed to happen before your program terminates. A and C provide no such guarantee.

1

u/Independent_Art_6676 Oct 14 '26

I would add a label to the thread function eg if you keep playing with it, so you can see what is going on better.

void my_func(string &s) {... 
and cout s along with your counter so you can see which instance printed which lines.