在C ++中声明一个成员函数的线程作为该类的成员

时间:2015-04-05 12:26:41

标签: c++ multithreading member-functions

如何在运行成员函数的类中声明一个线程? 我根据在线搜索尝试了几种方法: 这个

std::thread t(&(this->deQRequest));

std::thread t([this]{ deQRequest(); });

std::thread t(&this::deQRequest, this);

std::thread t(&this::deQRequest, *this);

它们都不起作用。

然后我尝试了以下代码,它可以工作:

    std::thread spawn() {
        return std::move(
            std::thread([this] { this->deQRequest(); })
            );
    }

但我的问题是,为什么会这样呢

   std::thread t([this]{ deQRequest(); });

不起作用?它总是提醒一个错误:"显式类型丢失,' int'假定"和"期待一个声明"

我的deQRequest函数是同一个类中的成员函数,我的类看起来像这样:

  class sender{
      public:
          void deQRequest(){
             //some execution code
          };
      private:
        // here I try to declare a thread like this:std::thread t([this]{ deQRequest(); });
   }

1 个答案:

答案 0 :(得分:0)

  

但我的问题是,为什么会这样呢

std::thread t([this]{ deQRequest(); });
     

不起作用?它总是提醒一个错误:      “显式类型缺失,'int'假设”和“预期声明”。

它不是有效的lambda函数语法。 thisdeQRequest的隐含参数,不能以这种方式传递。

std::thread's constructor reference开始,它需要一个函数参数,以及应该在那里传递的参数:

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );

你的班级

 class sender{
 public:
    void deQRequest(){
        //some execution code
    };
 private:
    void foo() { // I just assume you're using some private function
        // here I try to declare a thread like 
        // this:std::thread t([this]{ deQRequest(); });
    }

    std::thread theThread; // I also assume you want to have a `std::thread`
                           // class member.
 }; // <<< Note the semicolon BTW

声明一个成员函数,你需要std::bind()该成员函数到(你当前的)类实例:

    void foo() {
       theThread = std::thread(std::bind(&sender::deQRequest,this));
    }