将成员函数传递给std :: thread [英] Passing member functions to std::thread

查看:773
本文介绍了将成员函数传递给std :: thread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

启动成员函数的线程

围绕着新的std ::线程库在c ++ 11和我碰到一个问题。当我试图传递一个类函数到一个新的线程,它给我一个错误(我现在没有确切的错误文本,因为我离开家)
我有一个类似

I have recently been playing around with the new std::thread library in c++11 and I came across a problem. When i try to pass a classes function into a new thread, it gives me an error (I dont have the exact error text right now since im away from home) I had a class like this

class A
{
    void FunctA();
    void FunctB();

    void run()
    {
        std::thread t(FunctA);
        std::thread r(FunctB);
    }
}

我做错了什么?

推荐答案

class A
{
    void FunctA();
    void FunctB();

    void run()
    {
        std::thread t(&A::FunctA, this);
        std::thread r(&A::FunctB, this);
    }
};

成员函数的指针与函数的指针不同,调用它们的语法也不同,并需要类的实例。您可以将指向实例的指针传递给 std :: thread 构造函数的第二个参数。

Pointers to member functions are different from pointers to functions, syntax of calling them is different, as well, and requires instance of class. You can just pass pointer to instance as second argument of std::thread constructor.

这篇关于将成员函数传递给std :: thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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