1

我的 gcc 编译器支持 C++ 14。

场景:
我想知道是否有一种方法可以强制取消阻塞呼叫并std::thread安全地停止我的呼叫。

代码:

// 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
    }
}

在上面的代码ReadValue中是一个阻塞调用,它进入一个库并在 fd 上读取一些我无法控制的与设备驱动程序相关的代码。

问题:
我需要StopThread能够停止线程并取消正在阻塞的调用ReadValue我怎样才能做到这一点?C++ 11 或 14 中有什么方法吗?

PS:
可能std::async是一个解决方案?但我想知道是否有更好的方法。如果std::async是最好的方法,那么如何在这种情况下有效地使用它而不会造成不良的副作用。

4

1 回答 1

2

在 Linux 上,您可以获得本机线程句柄和使用pthread_cancel函数。前提是线程没有禁用可取消性并且线程在取消点被阻塞。您必须仔细阅读文档以了解所有注意事项。

于 2018-07-12T16:50:40.893 回答