繁体   English   中英

在C ++中将成员函数的线程声明为类的成员

[英]declare a thread of member function as a member of the class in C++

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

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(); });
   }

但我的问题是,为什么

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

不起作用? 它总是会提示错误:“缺少显式类型,假定为'int'”和“预期为声明”。

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

std::thread的构造函数引用开始,它带有一个函数参数以及应在此处传递的参数:

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));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM