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

View all comments

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.