gpt4 book ai didi

c++ - 在对象构造函数中初始化boost线程?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:07 25 4
gpt4 key购买 nike

我想为 boost 线程编写一个包装器来专门化一个线程模型。我的 run() 函数将成为使用 boost::thread 作为聚合线程对象的同一类的成员函数。考虑:

class Thread {
public:
Thread(...) : m_thread(&Thread::run, this) {}

private:
void run() { ... }
boost::thread m_thread;
};

This is potentially dangerous因为 this 还没有完全构建。但是,如果我可以保证 run() 使用的对象的所有成员都在 boost 线程初始化之前进行了初始化,这实际上可以被认为是安全的吗?

我能想到的保证安全的唯一解决方法是有一个子类来保证可以被 Thread 的构造函数使用的对象的完整构造:

class Thread {
public:
Thread(...) : m_impl(...), m_thread(&ThreadImpl::run, &m_impl) {}

private:
class ThreadImpl {
ThreadImpl(...) { }
void run() { ... }
}

ThreadImpl m_impl;
boost::thread m_thread;
};

有没有通用的方法来做到这一点? ThreadImpl 类对于这样一个微不足道的问题来说似乎有很多开销。

最佳答案

声明成员的顺序(不是初始化列表中的顺序,但要小心)是构造顺序。如果您最后声明线程成员,只要构建的所有成员足以建立一致的状态,您应该没问题。

但是,如果你不想依赖它,你可以在构造函数的末尾用这样的东西启动你的线程:

// Constructor
MyThread() {
// Initialize everything else...

boost::thread t(boost::bind(&MyThread::run, this));
m_thread.swap(t);
}

关于使用this指针的安全性,标准在12.6.2中说:

Note: because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized.

Member functions (including virtual member functions, 10.3) can be called for an object under construction.

您只需要避免访问尚未构建的内容即可。这可以包括在初始化所有基类之前调用​​成员函数:

class Derived : public Base {
public:
Derived()
: Base(foo()) // foo() undefined because base class not initialized
{
}

int foo() { return 0; }
};

关于c++ - 在对象构造函数中初始化boost线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com