简体   繁体   English

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

[英]cancelling std::thread using native_handle() + pthread_cancel()

I am converting a previous thread wrapper around pthreads to std::thread. 我正在将一个先前的线程包装器转换为pthreads到std :: thread。 However c++11 does not have any way to cancel the thread. 但是c ++ 11没有任何方法可以取消该线程。 I REQUIRE, nonetheless, to cancel threads since they may be performing a very lengthy task inside an external library. 尽管如此,我要求取消线程,因为它们可能在外部库中执行非常冗长的任务。

I was considering using the native_handle that gives me pthread_id in my platform. 我正在考虑使用native_handle,它在我的平台上给了我pthread_id。 I'm using gcc 4.7 in Linux (Ubuntu 12.10). 我在Linux中使用gcc 4.7(Ubuntu 12.10)。 The idea would be: 这个想法是:

#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;
}

The thread is canceled by an exception thrown by pthreads. 该线程被pthreads抛出的异常取消。

My question is: 我的问题是:

Will there be any problem with this approach (besides not being portable)? 这种方法会有问题吗(除了不便携)?

No, I don't think that you will not have additional problems than: 不,我认为你不会有额外的问题:

  • not being portable 不便携
  • having to program _very_very_ carefully that all objects of the cancelled thread are destroyed... 必须仔细编程_very_very_,取消线程的所有对象都被销毁...

For example, the Standard says that when a thread ends variables will be destroyed. 例如,标准说当一个线程结束时,变量将被销毁。 If you cancel a thread this will be much harder for the compiler, if not impossible. 如果你取消一个线程,这对编译器来说将更加困难,如果不是不可能的话。

I would, therefore recommend not to cancel a thread if you can somehow avoid it. 因此,如果您可以以某种方式避免它,我建议不要取消线程。 Write a standard polling-loop, use a condition variable, listen on a signal to interrupt reads and so on -- and end the thread regularly. 编写标准轮询循环,使用条件变量,监听信号以中断读取等等 - 并定期结束线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM