c++ - 带有 std::thread 和 this 的 ctor 初始值设定项列表

标签 c++ multithreading c++11 this initializer-list

我在构造函数的初始化列表中读到了一些关于“this”不安全的内容。我有一个相当大的应用程序,我跟踪了一些未定义的行为,以在构造函数的初始化列表中使用 std::thread 和“this”。当我将 std::thread 构造移出初始化列表并移入构造函数时,应用程序可以正常运行。

我试图用一个例子来重现这个问题,但它运行得很好。 谁能解释为什么 std::thread、'this' 和初始化程序列表的组合可能会产生未定义的行为。我认为这与调用 std::thread 构造函数时“this”未完全初始化有关,但这只是猜测。

我希望能够重现该问题。 在 ubuntu 16.04 上尝试使用 g++4.9.2 和 g++5.4。 我用 -g 和 -O0 编译来调试。还尝试使用 -O2 和 -O3。

#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>

//g++ -std=c++11 -g -O0 -pthread init_thread.cpp -o init_thread

/* ------------------------------------------------------------------------- +
 |   TEMPLATE FUNCTIONS
 + ------------------------------------------------------------------------- */
#if __cplusplus < 201402L
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif


/* ------------------------------------------------------------------------- +
 |   CLASSES
 + ------------------------------------------------------------------------- */
class X
{
public:
    X() = delete;

    X(int x) : x_(x)
    {
        t_ = std::thread(&X::foo, this);
        printf("Ctor X\n");
    }

    ~X()
    {
        {
            std::lock_guard<std::mutex> lck(mtxState_);
            state_ = State::terminated;
        }
        cv_.notify_one();
        if (t_.joinable())
        {
            t_.join();
        }
        printf("Dtor X\n");
    }

private:
    enum class State
    {
        suspended,
        running,
        terminated
    };

    int x_;
    mutable std::mutex mtxState_;
    State state_ { State::running };
    mutable std::condition_variable cv_;
    std::thread t_;

    void foo()
    {
        while (state_ != State::terminated)
        {
            switch (state_)
            {
                case State::suspended:
                    {
                        std::unique_lock<std::mutex> lck(mtxState_);
                        cv_.wait(lck, [this] { return state_ != State::suspended; });
                    }
                    break;
                case State::running:
                    {
                        printf("do something X...\n");
                        std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    }
                default:
                    break;
            }
        }
    };
};


class I
{
public:
    I() = delete;
    I(int i) {};
};


class A : I
{
public:
    A() = delete;

    A(int a) : I(a), a_(a), x_obj_with_thread_(make_unique<X>(15)), t_(std::thread(&A::foo, this))
    {
        printf("Ctor A\n");
    }

    ~A()
    {
        {
            std::lock_guard<std::mutex> lck(mtxState_);
            state_ = State::terminated;
        }
        cv_.notify_one();
        if (t_.joinable())
        {
            t_.join();
        }
        printf("Dtor A\n");
    }

private:
    enum class State
    {
        suspended,
        terminated
    };

    int a_;
    mutable std::mutex mtxState_;
    State state_ { State::suspended };
    mutable std::condition_variable cv_;
    std::thread t_;
    std::unique_ptr<X> x_obj_with_thread_;

    void foo()
    {
        while (state_ != State::terminated)
        {
            switch (state_)
            {
                case State::suspended:
                    {
                        std::unique_lock<std::mutex> lck(mtxState_);
                        cv_.wait(lck, [this] { return state_ != State::suspended; });
                    }
                    break;
                default:
                    printf("do something A...\n");
                    break;
            }
        }
    };
};

class B : I
{
public:

    B() = delete;

    B(int b) : I(b), b_(b), x_obj_with_thread_(make_unique<X>(15))
    {
        t_ = std::thread(&B::bar, this);
        printf("Ctor B\n");
    }

    ~B()
    {
        {
            std::lock_guard<std::mutex> lck(mtxState_);
            state_ = State::terminated;
        }
        cv_.notify_one();
        if (t_.joinable())
        {
            t_.join();
        }
        printf("Dtor B\n");
    }

private:
    enum class State
    {
        suspended,
        terminated
    };

    int b_;
    mutable std::mutex mtxState_;
    State state_ { State::suspended };
    mutable std::condition_variable cv_;
    std::thread t_;
    std::unique_ptr<X> x_obj_with_thread_;

    void bar()
    {
        while (state_ != State::terminated)
        {
            switch (state_)
            {
                case State::suspended:
                    {
                        std::unique_lock<std::mutex> lck(mtxState_);
                        cv_.wait(lck, [this] { return state_ != State::suspended; });
                    }
                    break;
                default:
                    printf("do something B...\n");
                    break;
            }
        }
    };
};


void testA()
{
    for (int i=0; i < 100000; i++)
    {
        printf("A iteration %i\n", i);
        A a(15);
    }
}

void testB()
{
    for (int i=0; i < 100000; i++)
    {
        printf("B iteration %i\n", i);
        B b(15);
    }
}

int main() 
{
    std::thread a(testA);
    std::thread b(testB);
    a.join();
    b.join();
    return 0;
}

最佳答案

在构造函数 member-init-list 中(这是构造函数定义中原型(prototype) (X(int x)) 和主体 ({...}) 之间的东西的正式名称),直到点表明你访问的数据成员已经初始化。数据成员的初始化顺序不是由它们在 member-init-list 中的顺序定义的,而是它们在类定义中的顺序定义的(例如,如果前者的顺序与后者的顺序不匹配,Clang 会发出警告)。

所以原则上,只要线程是最后一个类成员,这是完全可用的(除非在构造函数体中执行任何额外的初始化,这是在 member-init-list 运行完之后执行的。)

查看您的 A 类代码,您似乎遇到了我描述的初始化顺序错误:您的 unique_per 成员是在线程之后定义的,但您错误地认为将 unique_ptr 放在 member-init-list 中的第一位会发生变化它们的初始化顺序。事实并非如此,您可能会遇到与此相关的问题。在 B 中,线程首先被默认初始化:将它留在成员初始化列表之外并不意味着它不是首先被默认初始化!然后在构造函数体中,你实际上启动了一个运行函数的线程。

关于c++ - 带有 std::thread 和 this 的 ctor 初始值设定项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028621/

相关文章:

C++11 for 循环语法不能正常工作

c++ - 容器的访问比较器(C++/STL)

c++ - Qt 如何向服务器发送 https 请求?

c++套接字接受,连接的客户端列表

c++ - C++11 自定义对象中有序集缺少值

c++ - 构造函数继承和直接成员初始化

c++ - 为什么允许跳过变量定义(使用 goto)?

regex - System.RegularExpressions.TRegEx 是线程安全的吗?

python - Popen 在 Python 2.7 中不返回

java - 了解 Android 中的 Runnable