MeVisLab Toolbox Reference
asio::ResourceDestructionGuard Class Referencefinal

A guard that protects resources of a given class from being detroyed if another thread still works with them. More...

#include <ResourceDestructionGuard.h>

Public Member Functions

 ResourceDestructionGuard ()
 
 ~ResourceDestructionGuard ()
 
WeakHandle handle () const
 

Detailed Description

A guard that protects resources of a given class from being detroyed if another thread still works with them.

One might think this is not necessary, there is std::shared_ptr for it. But - for objects that don't have shared ownership which are out of control regarding construction/destruction (think of MeVisLab modules controlled by MeVisLab), you need to make sure that MeVisLab doesn't destroys your object while threads are working with it.

Synopsis:

class MyModule : public ml::Module
{
private:
// called from main thread somehow (so instance existence guaranteed)
void foo()
{
auto handle = guard.handle();
// delegate work to a background thread (this is just exemplary code for this demonstration,
// do not do it in this manner, the important thing is that the code is executed by
// a different thread than the main thread).
// and pass the guard's handle as capture
std::thread([handle] {
// ... some calculations ...
// now, what if the user deleted this instance of MyModule in the GUI in the meantime?
// there is nothing that protects the ml::Module from being destructed.
// BUT, there is asio::ResourceDestructionGuard which deletes a mutex-protected shared_ptr
// on destruction while the given handle has a weak_ptr on that shared_ptr...
auto lock = handle.lock(); // we acquire a lock (which technically is a lock of the mutex and the shared_ptr from weak_ptr)
if (lock) {
// Now, we are sure that the module is not gone already and is protected
// from being destructed by the shared mutex. We can safely access class resources
// The module's destructor (if invoked) will wait until we are finished.
my_resource = "hallo";
}
else {
// The module has gone, we MUST NOT access any members
}
});
}
std::string my_resource;
asio::ResourceDestructionGuard guard; // Be sure to define this as last member of the class.
};
A guard that protects resources of a given class from being detroyed if another thread still works wi...
Base class for an image processing module of the ML.
Definition: mlModule.h:156

Definition at line 67 of file ResourceDestructionGuard.h.

Constructor & Destructor Documentation

◆ ResourceDestructionGuard()

asio::ResourceDestructionGuard::ResourceDestructionGuard ( )

◆ ~ResourceDestructionGuard()

asio::ResourceDestructionGuard::~ResourceDestructionGuard ( )

Member Function Documentation

◆ handle()

WeakHandle asio::ResourceDestructionGuard::handle ( ) const

The documentation for this class was generated from the following file: