繁体   English   中英

如何在类内创建线程?

[英]How to create a thread inside a class?

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“功能”:未声明的标识符

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

我不知道为什么您的朋友功能查找在这种情况下不起作用,也许有人知道。
但是,存档所需内容的最快方法是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;

};
....

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

输出:

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

编辑:

根据评论中的讨论,我在此处发布的第一个代码存在一个问题,即您无法调用成员函数或访问friend 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;
}

暂无
暂无

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

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