Launching a member function on a background can be done as follows. In this example we have a class called ExampleClass with a member function mymethod().
#include <thread> ExampleClass *ec = new ExampleClass; std::thread thread(&ExampleClass::myMethod, ec); thread.detach();And finally a complete sample to demonstrate the concept:
A few words of caution// required to use the std::thread class #include <thread> // not required for threading but used in // this example to get console input #include <iostream> #include <string> class ExampleClass { public: void myMethod(); }; void ExampleClass::myMethod() { printf("thread running!"); } int main(int argc, _TCHAR* argv[]) { ExampleClass *ec = new ExampleClass; std::thread thread(&ExampleClass::myMethod, &ec); thread.detach(); std::string line; std::getline(std::cin, line); }
Be sure that the object outlives the thread function i.e. by allocating it on the heap. Otherwise if you thread function tries to access member variables it will access invalid memory and potentially cause access violations!
In the example above I new it up and do not bother to dispose it as my application exits anyway. In more complex programs you will need to consider where to free this memory safely.
0 comments:
Post a Comment