I'm a bit unsure about writing a move constructor, for a class which is executing a member function, whom is running in a member thread (copy constructor/assign is been deleted, as one of this as an afaik obvious reason).
I know so far that I'm copying a object pointer to the inital thread constructor, so he can use the right function in the right context.
this->worker = std::thread (&class::working_loop,this);
So I assume my question is does the std::thread move constructor change the function context?
I doubt that, but I'm not sure how sophisticated the thread move constructor is.
Otherwise I assume, I have to stop the thread in the old object, move/copy all relevant data, and create a new thread on the new object?
(To the essential stripped example below)
class Directory
{
private:
std::thread worker;
std::atomic<bool> stop;
void working_loop();
public:
void start_monitor();
void stop_monitor();
Directory (Directory &&dir);
Directory(const Directory&) = delete;
Directory& operator= (const Directory&) = delete;
~Directory();
};
void Directory::start_monitor()
{
stop = false;
worker = std::thread (&Directory::working_loop,this);
}
void Directory::stop_monitor()
{
stop = true;
if (worker.joinable())
{
worker.join();
}
else
{
std::cerr << "Warning thread " << worker.get_id() << " already joined!" << std::endl;
}
}
Edit: Working loop connects to a database to get further data belonging to the object(i.e. directory) and uses them for later directory scanning/notification callbacks, while the class user uses it to organise multiple directories. The class type should be able to be std::vector::emplace_back ed into a vector for the class user.
worker = std::thread (&Directory::working_loop,this);
Here be danger when moving...
The thread of execution is bound to a member function on a specific instance of on object. If the object changes location in memory, all sorts of trouble awaits your thread.
Don't just move it.
You don't show the implementation of the thread's function working_loop()
, I'll assume it only requires the use of the std::atomic<bool> stop
to communicate the condition to stop the thread's execution. Consider alternatives to the implementation of the thread being bound as a member function (i.e. free functions, or static functions). Then use thread communication mechanisms such as condition_variables
, shared mutex
objects or even share the stop
variable.