C++ std::thread and method class [duplicate]

2019-08-13 22:25发布

This question already has an answer here:

i'm trying to use a function of a class with std::thread

The follow code snippet return an error

MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works

std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here

I need to make a thread with that specific pointer to the class: MyClass_ptr

So, is there a way to use a method of that class using this specific pointer ?

If it's useful here is the full code compiled with Microsoft Visual Studio 2013

#include "stdafx.h"

#include <iostream>
#include <thread>

class MyClass 
{

public:
    void MyFunction();
    void MyOtherFunction();

};

void MyClass::MyOtherFunction()
{
    std::cout << "Inside MyOtherFunction" << std::endl;
    std::cin.get();
}

void MyClass::MyFunction ()
{
    std::cout << "Inside MyFunction" << std::endl;
    std::cin.get();
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass *MyClass_ptr = new MyClass;

    MyClass_ptr->MyFunction(); // Works
    std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
    std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here


    delete MyClass_ptr;
    MyClass_ptr = nullptr;

    return 0;
}

3条回答
冷血范
2楼-- · 2019-08-13 22:39

Yes you will need to use bind. The following example is for boost bind but you could always use the C++11 version of bind.You could use it like this

boost::thread t(boost::bind(&sommeclass::someMethod, ptr_instance_of_someclass,parameters_if_any));

so in your case it will be

 boost::thread ThreadA(boost::bind(MyClass::MyFunction,MyClass_ptr)); 
查看更多
Bombasti
3楼-- · 2019-08-13 22:43

You need to pass an object on which the member function will be called (remember, every non-static member function has an implicit this parameter) :

#include <thread>

class MyClass
{
    public:
    void MyFunction();
    void MyOtherFunction();
};

int main()
{
    MyClass *MyClass_ptr = new MyClass;

    std::thread ThreadA(&MyClass::MyFunction, MyClass_ptr);
    std::thread ThreadB(&MyClass::MyOtherFunction, MyClass_ptr );
}
查看更多
啃猪蹄的小仙女
4楼-- · 2019-08-13 22:46

You could use a closure.

std::thread ThreadA( [MyClass_ptr](){ 
    MyClass_ptr->MyFunction(); 
});
查看更多
登录 后发表回答