1

My gcc compiler supports C++ 14.

Scenario:
I want to know if there is a way I can force cancel out of a blocking call and stop my std::thread safely.

Code:

// Member vars declared in MyClass.hpp
std::atomic<bool> m_continue_polling = false;
std::thread       m_thread;

StartThread() {
    m_continue_polling = true;
    m_thread = std::thread { [this] {
        while (m_continue_polling) {
           int somevalue = ReadValue(); // This is a blocking call and can take minutes
        }
    }};
}

StopThread() {

    m_continue_polling = false;
    try {
        if (m_thread.joinable()) {
            m_thread.join();
        }
    }
    catch(const std::exception & /*e*/) {
        // Log it out
    }
}

In above code ReadValue is a blocking call which goes into a library and reads on a fd which some device driver related code which I have no control on.

Question:
I need StopThread to be able to stop the thread and cancel the call that is blocking on ReadValue. How can I do this? Is there some way in C++11 or 14?

PS:
Probably std::async could be a solution? But I wish to know if there are better ways. If std::async is the best approach then how to effectively use it this scenario without causing bad side effects.

TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159
  • 1
    C++ sadly doesn't have support for non-cooperative way of terminating a single thread – Zereges Jul 12 '18 at 16:48
  • 1
    If it can take minutes, I would consider to export the blocking functionality (int ReadValue()) to a second small executable, that is possible to terminate, and execute it from the code asyncronically, waiting for the result during sampling m_continue_polling in intervals (or with a combination of conditional variable if you don't like the idea of polling). – Amit G. Jul 12 '18 at 18:21

1 Answers1

2

On Linux, you can get the native thread handle and use pthread_cancel function. Provided the thread did not disable cancelability and that the thread is blocked in a cancellation point. You will have to read the documentation carefully to understand all the caveats.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • But is that actually "safe" though? What happens if the thread has locked a mutex? What happens to the destructor calls to all stack object in that thread? – Nicol Bolas Jul 12 '18 at 16:58
  • @NicolBolas You will have to read the documentation carefully, which I am not going to cite here. `glibc` throws an exception, so your mutex is going to be unlocked if a scoped lock is used. – Maxim Egorushkin Jul 12 '18 at 17:07
  • ok. as I expected. there are potential ways but with possible side effects – TheWaterProgrammer Jul 13 '18 at 07:04