相关疑难解决方法(0)

C++ 0x线程中断

根据C++ 0x最终草案,没有办法请求线程终止.也就是说,如果需要,我们需要实施一个自己动手的解决方案.

另一方面,boost :: thread提供了一种以安全方式中断线程的机制.

在您看来,什么是最好的解决方案?设计自己的合作"中断机制"还是本土的?

c++ multithreading c++11

56
推荐指数
7
解决办法
3万
查看次数

使用 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++ ×2

c++11 ×2

gcc ×1

multithreading ×1

pthreads ×1

stdthread ×1