Commit 17846567 authored by Guillaume Roguez's avatar Guillaume Roguez

utils: improve getGlobalInstance()

- thread-safe
- limit respawn (no limit by default)

Refs #64903

Change-Id: Ie9b2465b6d4b064fa82454d389d4269805f0145d
parent 158da98b
......@@ -33,6 +33,7 @@
#include <type_traits>
#include <memory>
#include <mutex>
#include <cstddef> // for size_t
namespace ring {
......@@ -52,17 +53,30 @@ using enable_if_base_of = typename std::enable_if<std::is_base_of<T, U>::value,
* Return a shared pointer on an auto-generated global instance of class T.
* This instance is created only at usage and destroyed when not,
* as we keep only a weak reference on it.
* But when created it's always the same object until all holders release their sharing.
* But when created it's always the same object until all holders release
* their sharing.
* An optional MaxRespawn positive integer can be given to limit the number
* of time the object can be created (i.e. different instance).
* Any negative values (default) block this effect (unlimited respawn).
* This function is thread-safe.
*/
template <class T>
template <class T, signed MaxRespawn=-1>
std::shared_ptr<T>
getGlobalInstance()
{
static std::recursive_mutex mutex; // recursive as instance calls recursively
static std::weak_ptr<T> wlink;
std::unique_lock<std::recursive_mutex> lock(mutex);
if (wlink.expired()) {
static signed counter {MaxRespawn};
if (not counter)
return nullptr;
auto link = std::make_shared<T>();
wlink = link;
if (counter > 0)
--counter;
return link;
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment