rajkiran rajkiran - 12 days ago 9
C++ Question

This thread example doesn't work. Please help me find out why?

I am trying to compile the following example and I am getting an error. Below is the code :

class A {
private:
//variables

public:
A(int a,int b){
//assign variables
}
void C(){
// do something
}
int D(){
// do something
}
void E(){
}
};
int main(){
A* temp = new A(a,b);
temp->C;
std::thread t;
t(&A::D,A);
t.join();
temp->E;
return 0;
}


I get the following error when I compile the above code with
pthread
and
std=c++11
flags. The following is the error message :

expected primary-expression before ‘)’ token
t(&A::D,A);

Answer

Adding some things here as an answer.

The first part of the question was an answer to the original comment. The constructor for std::thread takes the function to run. There's no additional operator() within the thread class, so to run A::d, you need to do:

std::thread t(A::d, a);

That will start the thread running that function.

The follow on question of how to do an array of threads... Since this is c++, consider a vector instead. If you have a vector of A, or A* you could do something like.

std::vector<std::thread> threads;
std::vector<A> as;
... initialize as, for instance as.push_back(A(...)); ...
for (auto&& a : as) { threads.emplace_back(A::d, &a); }
for (auto&& t : threads) { t.join(); }

Note: when using emplace_back, the arguments are the constructor arguments for the type in the vector, not objects of that type. You could also use emplace for setting up the vector<A>. If you want a vector<A*>, then you don't need to do &a on the thread construction.