Passing pointers to threads without being out of scope
c++, multithreading
Solution
If the object's lifetime is simply bound to the scope of `main`, then that's easy - just make sure you've stopped and joined all the threads before destroying the object. This can be better enforced either by managing the object with a smart pointer scoped within `main` or, more simply, by giving the object automatic lifetime within `main`:
void thread_func(Cdefine *);
int main()
{
Cdefine thing;
thing.Init();
std::thread thread1(thread_func, &thing);
std::thread thread2(thread_func, &thing);
// do stuff
thread1.join();
thread2.join();
// Now it's safe to destroy the object
}
In a more complicated situation, where you can't simply bind the object to a wider scope than that of the threads, you could consider managing it with `std::shared_ptr` (or `std::tr1::shared_ptr` or `boost::shared_ptr` if you're stuck with the pre-2011 language). For example:
void thread_func(std::shared_ptr<Cdefine> p);
void spawn_threads()
{
std::shared_ptr<Cdefine> p = std::make_shared<Cdefine>();
p->Init();
std::thread thread1(thread_func, p);
std::thread thread2(thread_func, p);
thread1.detach();
thread2.detach();
// The threads can carry on doing their thing, and it's safe to
// drop our shared pointer. The object will be deleted when the
// last thread drops its pointer to it.
}
As an aside, why on earth do you need to call an `Init` function after constructing the object? Why not initialise it in the constructor, since that's what a constructor is for?
Problem
I am given a pre-defined .lib files of pre-defined classes/functions. I will need to create a: ``` Cdefined *p = new Cdefined; p->Init(); ``` in the main() program to init my class object before calling my thread. However I realised that in each of my threads, I will have to call: ``` p->doProcess(); ``` to run a segment of the code, for each of the threads. However, this function will not work unless i call `p->Init()`. Since now I have at least 2 scopes of p (one created in `main()`, and N of them in N threads), how do I go about designing my thread, such that the class can be passed in without scope errors? [My constrain is that `p->Init()` has to be called in `main()`]