小编Joã*_*eal的帖子

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

我正在将先前围绕 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 …
Run Code Online (Sandbox Code Playgroud)

c++ gcc pthreads c++11 stdthread

7
推荐指数
1
解决办法
4251
查看次数

标签 统计

c++ ×1

c++11 ×1

gcc ×1

pthreads ×1

stdthread ×1