c++ – What is the best way to kill a hung thread?

Question:

std::thread * tr1;
tr1 = new std::thread([&]()
{
    function();     // функция что то считает
    Sleep(3000000); // допустим это означает зависание
});

The running thread hung for some reason, the timer determined that the thread was running for a longer time. How can a thread be killed so that it does not hang in memory and perform calculations? There are no mutexes in the thread, etc. No variables can be destroyed, a pointer is passed there, which, when it is detected that the timer has been exceeded, is set to zero. The stream no longer contacts anyone or anything.

How can it be killed or paused?

Answer:

std::thread does not support this feature because it is highly discouraged to do so. If you have a thread hanging, this is already bad, and this is the problem that needs to be fixed, and not trying to make crutches with killing threads.

If your code is running on a thread, periodically check the thread exit flag or use some other synchronization method. If it is not your code that is being executed, then in no case do not touch the thread. No one knows what might be in someone else's code.

If you need killable threads, you can use boost::thread . Or dig into the native handle std::thread::naitive_handle and use the axis-specific functions.

Scroll to Top