【问题标题】:is there any chance an exception happens during variable definition?在变量定义期间是否有可能发生异常?
【发布时间】:2016-03-23 02:16:47
【问题描述】:
class ThreadGuard {
public:
    ThreadGuard(std::thread &t_): t(t_) {}
    ~ThreadGuard()
    {
        if(t.joinable()) 
            t.join();
    }
private:
    std::thread &t;
};

void func()
{
    std::thread my_thread(f);
    ThreadGuard thread_guard(my_thread);
}

我尝试使用 ThreadGuard 对象来保证函数在线程正常终止之前不会退出。但是如果在创建 thread_guard 对象之前发生异常怎么办。

【问题讨论】:

  • 应该没问题。如果抛出异常,意味着线程构造失败,那么线程不应该运行,函数应该退出。对吗?
  • −1 if(t.joinable) 不是真正的代码
  • 对不起,我弄错了。应该是if(t.joinable())
  • 线程构造成功,thread_guard构造失败。线程已经运行。

标签: c++ multithreading exception-handling


【解决方案1】:

RAII的意义在于让资源获取对象真正拥有资源。你的ThreadGuard 仍然不能保证线程实际上是被保护的。你会想要更多类似的东西:

class ThreadGuard {
    std::thread t;

public:
    ~ThreadGuard() {
        if (t.joinable()) t.join();
    }

    // constructors and assignment as appropriate to actually
    // initialize the thread object
};

这样,你可以写:

ThreadGuard thread_guard(f);

不用担心。

【讨论】:

  • 感谢您的回答。但我不太明白如何实现适当的构造函数。我想初始化成员std::thread t 的唯一正确方法是从类std::thread 继承并直接在我自己的类的构造函数中调用它的构造函数。如果是这种情况,我需要传递一个类型的参数......,我不知道如何调用它,函数,可调用对象或类似的东西,给我的构造函数。这对我来说有点复杂。
猜你喜欢
  • 1970-01-01
  • 2013-10-28
  • 1970-01-01
  • 2021-12-20
  • 2010-09-12
  • 1970-01-01
  • 2011-01-27
  • 2016-05-28
  • 1970-01-01
相关资源
最近更新 更多