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

标签 c++ gcc c++11 pthreads 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;
}

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

我的问题是:

这种做法会不会有什么问题(除了不可移植)?

最佳答案

不,我认为您不会遇到以下问题:

  • 不可携带
  • 必须_非常_非常_仔细地编程以销毁已取消线程的所有对象...

例如,标准说当一个线程结束时,变量将被销毁。如果您取消一个线程,这对编译器来说将更加困难,如果不是不可能的话。

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

关于c++ - 使用 native_handle() + pthread_cancel() 取消 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531241/

相关文章:

c++ - c++ 14 中的 vector<string> 或 vector<shared_ptr<string>>

c++ - 如何让 SonarQube 与 SVN 服务器 v1.6.11 一起工作?

c++ - 是否可以在基于 Linux 的系统上使用 gcc 或 g++ 进行静态编译?

c - gcc 查找已安装的库

c++ - std::size_t 大小的一致性如何

c++ - 是否可以使用 Boost.Coroutine 嵌套协程?

c++ - 在函数映射容器 : automatic deduction fails with compiler error 中重载 C++ 函数返回类型

c++ - Winsock2:select()函数给出 "invalid arguement error"(错误10022)?

c++ - 在 std::map 中获取所有唯一映射值的最快方法

使用优化标志编译 C