Drake
scoped_singleton.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <memory>
4 #include <mutex>
5 
8 
9 namespace drake {
10 
11 /**
12  * Provides thread-safe, global-safe access to a shared resource. When
13  * all references are gone, the resource will be freed due to using a weak_ptr.
14  * @tparam T Class of the resource. Must be default-constructible.
15  * @tparam Unique Optional class, meant to make a unique specialization, such
16  * that you can have multiple singletons of T if necessary.
17  *
18  * @note An example application is obtaining license for multiple disjoint
19  * solver objects, where acquiring a license requires network communication,
20  * and the solver is under an interface where you cannot explicitly pass the
21  * license resource to the solver without violating encapsulation.
22  */
23 template <typename T, typename Unique = void>
24 std::shared_ptr<T> GetScopedSingleton() {
25  // Confine implementation to a class.
26  class Singleton {
27  public:
29 
30  Singleton() {}
31 
32  /*
33  * Acquire a reference to resource if no other instance exists.
34  * Otherwise, return a shared reference to the resource.
35  */
36  std::shared_ptr<T> Acquire() {
37  // Acquiring and releasing the resource via a centralized weak pointer,
38  // will be thread-safe. All constructions of T for this particular
39  // Singleton are assigned to this same weak_ref_; the empty-check,
40  // allocation, and weak_ref_ assignment are all guarded by the same
41  // critical section.
42  auto instance = weak_ref_.lock();
43  if (!instance) {
44  instance = std::make_shared<T>();
45  weak_ref_ = instance;
46  }
47  return instance;
48  }
49 
50  private:
51  std::weak_ptr<T> weak_ref_;
52  };
53  // Allocate singleton as a static function local to control initialization.
54  static never_destroyed<Singleton> singleton;
55  return singleton.access().Acquire();
56 }
57 
58 } // namespace drake
Definition: automotive_demo.cc:88
#define DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Classname)
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN deletes the special member functions for copy-construction, copy-assignment, move-construction, and move-assignment.
Definition: drake_copyable.h:33
Provides careful macros to selectively enable or disable the special member functions for copy-constr...