ctor初始化列表与std :: thread和

时间:2017-05-17 15:07:14

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

我已经阅读了一些关于这个'在构造函数的初始化列表中不安全。我有一个相当大的应用程序,我跟踪一些未定义的行为使用std :: thread与'这个'在构造函数的初始化列表中。当我将std :: thread构造移出初始化列表并进入构造函数时,应用程序可以正常工作。

我尝试用一​​个例子重现问题,但它运行得很完美。 任何人都可以解释为什么std :: thread的组合,'这个'和初始化列表可能会给出未定义的行为。我认为这与这个'在调用std :: thread构造函数时没有完全初始化,但这只是猜测。

我希望能够重现这个问题。 在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;
}

2 个答案:

答案 0 :(得分:2)

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

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

查看你的A类代码,似乎你遇到了我描述的初始化顺序错误:你的unique_per成员是在线程之后定义的,但是你错误地假设将unique_ptr放在member-init-list中会先改变他们初始化的顺序。它没有,你可能会遇到与此相关的问题。在B中,线程首先默认初始化:将其从member-init-list中删除并不意味着它不是第一次默认初始化!然后在构造函数体中,您实际上启动了一个运行函数的线程。

答案 1 :(得分:1)

根据标准,在初始化列表中使用成员函数可能导致未定义的行为:

  

可以调用成员函数(包括虚拟成员函数)   来自成员初始值设定项,但如果不是全部,则行为未定义   直接碱基在那时被初始化。

直接基类按从左到右的顺序初始化。

在你的例子中,问题是对象本身的初始化(this)没有完成,它已经传递给线程,由条件变量捕获并引用。

以下代码崩溃了一次,因为互斥锁未初始化,但我不能让它一致地重现:

class withthread
{
public:

    withthread(): b(false),t(std::thread(&withthread::func,this))

    {

    }
    ~withthread()
    {
        t.join();
    }
    void func()
    {
        int d=5;
        while ( --d  ) {
            std::unique_lock<std::mutex> l(m);
            v.wait(l,[this]() {this->b=true;return b;});
            cout << 2 << endl;
        }
    }
    std::thread t;
    std::mutex m;
    std::condition_variable v;
    bool b;
};

int main(){
    withthread w1 ;
    withthread *w ;
    w = new withthread();
    delete w;
    return 0;
}