Run Member Function in a Thread
C++11 thread and Lambda function really beautifies code that works with threads. If I have a class MyObj
with a member function DoWork()
:
class MyObj
{
public:
void DoWork();
void Think();
};
It has always been relatively effortless to spawn a thread, but if you need data from the underlying class then you'll need to pass it in as a pointer. If you need a lot of them then you'll need a struct
that captures all the classes you'll be working on.
With C++11:
void MyObj::Think()
{
std::thread handle([this] { DoWork(); });
handle.join();
}
The code fragment above captured this
and allows DoWork()
to be called directly, with full access to member variables of MyObj
class.