TheWaterProgrammer
TheWaterProgrammer

Reputation: 8249

Is it possible to cancel a blocking call in C++ 11 or 14?

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.

Upvotes: 1

Views: 1364

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

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.

Upvotes: 2

Related Questions