A "typical" approach to using pthread with a member function of a class in C++ would be to use inheritance (like suggested here https://stackoverflow.com/a/1151615/157344 ). But why not something like this:
#include <pthread.h>
template <class T, void * (T::*thread)()>
class Thread
{
public:
int create(T *that) { return pthread_create(&_handle, nullptr, _trampoline, that); };
pthread_t getHandle() const { return _handle; };
private:
static void * _trampoline(void *that) { return (static_cast<T *>(that)->*thread)(); };
pthread_t _handle;
};
It can be used like that:
class SomeClassWithThread
{
public:
int initialize() { return _thread.create(this); };
private:
void * _threadFunction();
Thread<SomeClassWithThread, &SomeClassWithThread::_threadFunction> _thread;
};
It has an advantage of NOT using virtual functions, so no vtable and less RAM used (I'm developing that for an MCU, not for a PC, so RAM usage matters). It also doesn't need virtual destructor.
Moreover I think it makes more sense, because a typical object rather HAS-A thread (composition), than IS-A thread (inheritance), right? (;
Is there any flaw with such design, as I haven't seen it suggested anywhere, as opposed to inheritance method? You'd definetely get a copy of _trampoline() for each instantiation but that's not much different from a virtual function call in inheritance version... I hope that create() and getHandle() would be inlined, as there's no reason not to...