The first problem is that your main function is spawning a thread, then immediately exiting. The thread will barely get a chance to run before the process terminates. So at a minimum you need to wait for the thread to finish, which you can do by adding newThread.join()
to the end of main
, thus:
int main(int argc, char* const argv[])
{
MyClass a;
A.push_back(a);
boost::thread newThread(&MyClass::DoSomething, &A.back());
newThread.join();
return 0;
}
The other issue is you've got the thread object in the same scope as main
, as a local variable. While you can do this in simple situations, you need to be careful about the scope of the boost::thread
object, which needs to give it a lifetime at least as long as you expect your thread to run.
In the case where an object needs to run a thread on a member function, you are probably better off encapsulating the thread object inside the object, and having a simple run()
method that starts the worker thread. That way you can encapsulate all the state and thread management in the one place, along with any mutexes and condition variables that you may need. A simple example would be something like:
class Worker
{
public:
Worker();
void start(int N)
{
m_Thread = boost::thread(&Worker::processQueue, this, N);
}
void join()
{
m_Thread.join();
}
// Worker thread where all processing occurs
void processQueue(int N);
private:
boost::thread m_Thread;
};
You would probably also want to add things like a flag that returns the thread state (eg. running, completed, waiting, etc).
I noticed your example uses a vector of object instances (ie. storing by value). Just be careful that you don't inadvertently end up performing operations that cause a copy to be implicitly created, as this can cause all sorts of problems with threads. (That's why the boost::thread
object is non-copyable.)
I've written an article on threading with Boost that explains the various ways you can create threads, including how to run threads on member functions (see type 5).