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

c – 使用native_handle()取消std :: thread pthread_cancel(),第1张

概述我正在将一个先前的线程包装器转换为pthreads到std :: thread. 但是c 11没有任何方法可以取消该线程.尽管如此,我要求取消线程,因为它们可能在外部库中执行非常冗长的任务. 我正在考虑使用native_handle,它在我的平台上给了我pthread_id.我在Linux中使用gcc 4.7(Ubuntu 12.10).这个想法是: #include <iostream>#in 我正在将一个先前的线程包装器转换为pthreads到std :: thread.
但是c 11没有任何方法可以取消该线程.尽管如此,我要求取消线程,因为它们可能在外部库中执行非常冗长的任务.

我正在考虑使用native_handle,它在我的平台上给了我pthread_ID.我在Linux中使用gcc 4.7(Ubuntu 12.10).这个想法是:

#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抛出的异常取消.

我的问题是:

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

解决方法 不,我认为你不会有额外的问题:

>不便携
>必须仔细编程_very_very_,取消线程的所有对象都被销毁…

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

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

总结

以上是内存溢出为你收集整理的c – 使用native_handle()取消std :: thread pthread_cancel()全部内容,希望文章能够帮你解决c – 使用native_handle()取消std :: thread pthread_cancel()所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1226392.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存