Let\'s say I have a class such as
class c {
// ...
void *print(void *){ cout << \"Hello\"; }
}
And then I have a vector of c
This is a bit old question but a very common issue which many face. Following is a simple and elegant way to handle this by using std::thread
#include
#include
#include
#include
class foo
{
public:
void bar(int j)
{
n = j;
for (int i = 0; i < 5; ++i) {
std::cout << "Child thread executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
int main()
{
int n = 5;
foo f;
std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
std::this_thread::sleep_for(std::chrono::milliseconds(20));
std::cout << "Main Thread running as usual";
class_thread.join();
std::cout << "Final value of foo::n is " << f.n << '\n';
}
Above code also takes care of passing argument to the thread function.
Refer std::thread document for more details.