How to execute a class member function in a separate thread using C++11 thread class?
Asked Answered
N

2

17

I'm trying to use the C++11's std::thread class to run a member function of a class to execute in parallel.

The header file's code is similar to:

class SomeClass {
    vector<int> classVector;
    void threadFunction(bool arg1, bool arg2);
public:
    void otherFunction();
};

The cpp file is similar to:

void SomeClass::threadFunction(bool arg1, bool arg2) {
    //thread task
}

void SomeClass::otherFunction() {
    thread t1(&SomeClass::threadFunction, arg1, arg2, *this);
    t1.join();
}

I am using Xcode 4.6.1 under Mac OS X 10.8.3. The compiler I am using is Apple LLVM 4.2 which came with the Xcode.

The above code does not work. The compiler error says that "Attempted to use deleted function".

On the line of thread creation it shows the following massage.

In instantiation of function template specialization 'std::__1::thread::thread<void (SomeClass::*)(bool, bool), bool &, bool &, FETD2DSolver &, void>' requested here

I'm new in C++11 and the thread class. Could someone help me?

Nevels answered 31/3, 2013 at 21:15 Comment(0)
D
22

The instance should be the second argument, like so:

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
Disconsolate answered 31/3, 2013 at 21:16 Comment(3)
It's worth to point out that the OPs code is useless if he calls .join() immediatly.Birt
Unfortunately this doesn't work if, for example, arg2 is a reference.Dolan
@Groosha: arg2 is an expression, and expressions are never references. However, if you would like to pass an argument by reference, you can wrap it in std::ref: std::thread(&X::f, this, std::ref(arg)).Disconsolate
A
1

I still had problems with the above answer (I think it was complaining it could not copy over a smart pointer?), so rephrased it with a lambda:

void SomeClass::otherFunction() {
  thread t1([this,arg1,arg2](){ threadFunction(arg1,arg2); });
  t1.detach();
}

Then it compiled and ran fine. AFAIK, this is just as efficient, and personally I find it more readable.

(Note: I've also changed join() to detach() as I expect that was the intent.)

Antimagnetic answered 24/4, 2015 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.