C ++ 11:std :: thread在一个类中,在构造函数中执行一个具有线程初始化的函数成员 [英] C++11: std::thread inside a class executing a function member with thread initialisation in the constructor

查看:767
本文介绍了C ++ 11:std :: thread在一个类中,在构造函数中执行一个具有线程初始化的函数成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用std :: thread从C ++ 11。我不能找到任何地方,如果可能有一个std :: thread在一个类中执行其中的一个函数成员。考虑下面的例子...
在我的try(下面),函数是run()。

I'm trying to use std::thread from C++11. I couldn't find anywhere if it is possible to have a std::thread inside a class executing one of its function members. Consider the example below... In my try (below), the function is run().

我使用gcc-4.4编译, c ++ 0x标志。

I compile with gcc-4.4 with -std=c++0x flag.

#ifndef RUNNABLE_H
#define RUNNABLE_H

#include <thread>

class Runnable
{
    public:
        Runnable() : m_stop(false) {m_thread = std::thread(Runnable::run,this); }
        virtual ~Runnable() { stop(); }
        void stop() { m_stop = false; m_thread.join(); }
    protected:
        virtual void run() = 0;
        bool m_stop;
    private:
        std::thread m_thread;
};


class myThread : public Runnable{
protected:
    void run() { while(!m_stop){ /* do something... */ }; }
};

#endif // RUNNABLE_H

我收到此错误:

Runnable.h|9|error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, Runnable* const)’|

传递指针时。

Runnable.h|9|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&Runnable::run’|


推荐答案

这种方法是错误的。

问题是,虽然对象仍在构建中,它的类型仍然不是最派生的类型,而是正在执行的构造函数的类型。这意味着当你启动线程时,对象仍然是一个 Runnable ,可以调用 run() Runnable :: run(),这是纯虚拟的,反过来会导致未定义的行为。

The problem is that while the object is still under construction its type is still not the most derived type, but the type of the constructor that is executing. That means that when you start the thread the object is still a Runnable and the call to run() can be dispatched to Runnable::run(), which is pure virtual, and that in turn will cause undefined behavior.

更糟糕的是,你可能会遇到一种错误的安全感,因为在某些情况下,正在启动的线程可能需要足够长的时间来使当前线程完成 Runnable 构造函数,并输入 myThread 对象,在这种情况下,新线程将执行正确的方法,但更改系统执行程序(不同数目核心或系统的负载,或任何其他无关的情况),程序将在生产中崩溃。

Even worse, you might run into a false sense of security, as it might be the case that under some circumstances the thread that is being started might take long enough for the current thread to complete the Runnable constructor, and enter the myThread object, in which case the new thread will execute the correct method, but change the system where you execute the program (different number of cores, or the load of the system, or any other unrelated circumstance) and the program will crash in production.

这篇关于C ++ 11:std :: thread在一个类中,在构造函数中执行一个具有线程初始化的函数成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆