Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 497
Raiyan Kabir Avatar asked Mar 31 '13 21:03

Raiyan Kabir


People also ask

What is multithreading C ++ 11?

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Before C++ 11, there is no built-in support for multithreaded applications.

How do you start a STD thread?

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object.


1 Answers

The instance should be the second argument, like so:

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
like image 112
Kerrek SB Avatar answered Oct 21 '22 16:10

Kerrek SB