使用 native_handle() + pthread_cancel() 取消 std::thread

Joã*_*eal 7 c++ gcc pthreads c++11 stdthread

我正在将先前围绕 pthreads 的线程包装器转换为 std::thread。但是 c++11 没有任何方法可以取消线程。尽管如此,我需要取消线程,因为它们可能在外部库中执行非常冗长的任务。

我正在考虑在我的平台中使用为我提供 pthread_id 的 native_handle。我在 Linux (Ubuntu 12.10) 中使用 gcc 4.7。这个想法是:

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

using namespace std;

int main(int argc, char **argv) {
    cout << "Hello, world!" << endl;

    auto lambda = []() {
        cout << "ID: "<<pthread_self() <<endl;
        while (true) {
            cout << "Hello" << endl;
            this_thread::sleep_for(chrono::seconds(2));
        }
    };

    pthread_t id;
    {
        std::thread th(lambda);

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

        id = th.native_handle();
        cout << id << endl;
        th.detach();
    }
    cout << "cancelling ID: "<< id << endl;

    pthread_cancel(id);

    cout << "cancelled: "<< id << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

线程被 pthreads 抛出的异常取消。

我的问题是:

这种方法会不会有什么问题(除了不便携)?

tow*_*owi 4

不,我认为您不会遇到除以下问题之外的其他问题:

  • 不便携
  • 必须_非常_非常_仔细地编程,以确保被取消线程的所有对象都被销毁......

例如,标准规定当线程结束时变量将被销毁。如果取消线程,这对于编译器来说会更加困难,甚至不可能。

因此,如果您能以某种方式避免的话,我建议不要取消线程。编写一个标准的轮询循环,使用条件变量,监听信号以中断读取等等——并定期结束线程。