0

I'm trying to understand how to work with threads and this simple code crashes with this error: enter image description here

the code:

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

void thread1()
{
    while (true)
    {
        cout << this_thread::get_id() << endl;
    }
}

void main()
{
    thread t1(thread1);
    thread t2(thread1);

    this_thread::sleep_for(chrono::seconds(1));

    t1.detach();
    t2.detach();
}

can someone please explain why it crashes after the detaches and how to fix this?

Guy Shilman
  • 45
  • 12

1 Answers1

1

The reason why you get an error is accessing CRT (C++ Runtime Library) after its deinitialization.

The worker threads use CRT by accessing std::cout. When the main thread leaves main function, the CRT library is unloading, but the worker threads are still trying to use it. Likely, there is a runtime check for it so you get a error message instead of just program crash.

It is better not to use detach method and be sure that all the threads you spawned are finished execution at program exit.

Andrey Nasonov
  • 2,619
  • 12
  • 26