如何在类内创建线程?

时间:2019-02-21 08:07:18

标签: c++

class MyClass
{
    public:
        friend void function(MyClass& mc)
        {
            std::cout << "Friend function from thread" << std::endl;
        }    
        void init()
        {
            thr = std::thread(function, this);
            thr.join();
        }

    private:
        std::thread thr;

};

  int main()
   {
    std::cout << "This is main function" << std::endl;
    MyClass nc;
    nc.init();

    return 0;
   }
  

错误C2065'功能':未声明的标识符

如何在不使用任何静态函数的类内创建线程?

2 个答案:

答案 0 :(得分:4)

我不知道为什么您的朋友函数的查找在这种情况下不起作用,也许有人知道。
但是,存档所需内容的最快方法是lamdba或声明函数。
例如。

class MyClass;
void function(MyClass& mc);
class MyClass
{
public:
    friend void function(MyClass& mc)
    ...
    void init()
    {
        // either do this
        thr = std::thread([this](){function(*this);});
        // or this note the std::ref. You are passing a reference. Otherwise there will be a copy
        thr = std::thread(&function, std::ref(*this));
        thr.join();
    }

private:
    std::thread thr;

};
....

答案 1 :(得分:0)

@mkaes击败了我,但我对您的function()进行了一些修改,使其接受指向该类的指针而不是引用。

  • 您不能像访问其他成员函数那样访问类内的好友函数。

    1. 问题在于,即使您在类中将其声明为朋友函数,您的朋友函数也没有全局声明。
    2. 因此,我们在类外部定义函数,并在内部保留一个Friend声明。
    3. 现在,由于function()不知道类MyClass,因此我们也必须转发声明MyClass类。

代码:

#include <iostream>
#include <thread>

class MyClass;

void function(MyClass* mc)
{
    std::cout << "Friend function from thread" << std::endl;
}

class MyClass
{
public:
    void init()
    {
       thr = std::thread(function, this);
       thr.join();
        // function(this);
    }
    friend void function(MyClass* mc);
private:
    std::thread thr;

};

int main()
{
    std::cout << "This is main function" << std::endl;
    MyClass nc;
    nc.init();

    return 0;
}

输出:

  

这是主要功能
  线程的好友功能

编辑:

根据评论中的讨论,我在这里发布的第一个代码有一个问题,即您无法调用成员函数或访问朋友function()内部的成员变量,因为该类是在以后定义的。为了解决这个问题,下面是替代方法。但是无论如何,@ mkaes从一开始就已经以这种方式回答了。

#include <iostream>
#include <thread>

class MyClass;
void function(MyClass* mc);

class MyClass
{
public:
    void init()
    {
       thr = std::thread(function, this);
       thr.join();
        // function(this);
    }
    friend void function(MyClass* mc)
    {
        std::cout << "Friend function from thread" << std::endl;
        mc->test();
    }
    int test(){}
private:
    std::thread thr;

};



int main()
{
    std::cout << "This is main function" << std::endl;
    MyClass nc;
    nc.init();

    return 0;
}