Reputation: 1
Coming from C# I was accustomed to create instances of a certain class and then calling threads executing a class method on that object, modifying its specific variables. Here's a c#-ish example:
class myclass
{
public:
int i = 0;
void method ()
{
i++;
}
}
// then my main
myclass obj1 = new myclass();
myclass obj2 = new myclass();
myclass obj3 = new myclass();
thread first = new thread (obj1.method);
thread second = new thread (obj2.method);
thread third = new thread (obj3.method);
Here i would expect i can access obj1.i, obj2.i, obj3.i and that they are = 1. I can't seem to be able to replicate this kind of behaviour in C++, probably is something very stupid, all i found as solution is use a static method, but that defeats the purpose of my code in the first place.
Upvotes: 0
Views: 1961
Reputation: 12928
Your main should look more like this
myclass obj1;
myclass obj2;
myclass obj3;
thread first(&myclass::method, obj1);
thread second(&myclass::method, obj2);
thread third(&myclass::method, obj3);
No need to heap allocate anything with new
.
To start a thread with a member function, you pass a pointer to the function and the object to invoke the member function on.
We also need to make sure we join the threads after.
first.join();
second.join();
third.join();
Edit
std::thread takes arguments by value by default, this means in the above code it will make copies of our objects and run the member functions on the copies.
If we want to make the member function run on the actual object we passed in we need to make use of a std::reference_wrapper
like so.
thread first(&myclass::method, std::ref(obj1));
A bit tired, oversight from my part. But now updated.
Upvotes: 4
Reputation: 81
I think this code do what you want:
#include <string>
#include <iostream>
#include <thread>
using namespace std;
class myclass {
public:
myclass(int _i) {
this->i = _i;
}
int i = 0;
void method () {
i++;
cout << "Method " << i << "\n";
}
};
int main()
{
myclass obj1(1);
myclass obj2(2);
myclass obj3(3);
thread t1(&myclass::method, obj1);
thread t2(&myclass::method, obj2);
thread t3(&myclass::method, obj3);
//Wait for finish all threads
t1.join();
t2.join();
t3.join();
return 0;
}
Upvotes: 0