Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Wednesday, 13 August 2014

Starting a C++ thread using a member function

Today I thought I'd share something that I have found useful on many occasions, that is launching a member function on a background thread in C++. Sometimes you can get away with simply firing up a normal thread and passing the current object pointer through as a parameter, however often this just isn't enough.

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:
// 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);
}

A few words of caution

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.