I need to make a thread that should run for the duration of the time a class exists. The thread should be destroyed with the class. Would it be wise to code with this general design (join in destructor)? Should I use a detached thread instead possibly?
class A {
public:
A() { pthread_create(m_thread, ...); }
~A() { pthread_join(m_thread, ...); }
private:
pthread_t m_thrad;
};
Lastly, can I use a member function to spawn off the thread, or does it have to be a static or global function?
If you access data from your class A from within the thread then you must join it in the destructor. A detached thread would otherwise access the class data after it has been destroyed which is simply undefined behavior.
Your thread function must be static or global. But you can pass your class’ this pointer as arg parameter to pthread_create and static_cast it back in your thread main function and call a normal method on your class. So you have a very slim static function: