ThreadLocalInstance.hpp
Go to the documentation of this file.
1 // @formatter:off
2 //
3 // Balau core C++ library
4 //
5 // Copyright (C) 2008 Bora Software (contact@borasoftware.com)
6 //
7 // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003.
8 // See the LICENSE file for the full license text.
9 //
10 
16 
17 #ifndef COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE
18 #define COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE
19 
20 #include <boost/thread/tss.hpp>
21 
22 namespace Balau::Concurrent {
23 
27 template <typename T, typename Enable = void> class ThreadLocalInstance;
28 
30 template <typename T>
31 class ThreadLocalInstance<T, typename std::enable_if<std::is_default_constructible<T>::value>::type> {
35  public: T & operator () () {
36  if (!instance.get()) {
37  instance.reset(new T);
38  }
39 
40  return *instance.get();
41  }
42 
46  public: T & operator () (std::function<T * ()> instantiate) {
47  if (!instance.get()) {
48  instance.reset(instantiate());
49  }
50 
51  return *instance.get();
52  }
53 
55 
56  private: boost::thread_specific_ptr<T> instance;
57 };
59 
61 template <typename T>
62 class ThreadLocalInstance<T, std::negation<typename std::enable_if<std::is_default_constructible<T>::value>::type>> {
66  public: T & operator () (std::function<T * ()> instantiate) {
67  if (instance.get()) {
68  instance.reset(instantiate());
69  }
70 
71  return *instance.get();
72  }
73 
75 
76  private: boost::thread_specific_ptr<T> instance;
77 };
79 
80 } // namespace Balau::Concurrent
81 
82 #endif // COM_BORA_SOFTWARE__BALAU_CONCURRENT__THREAD_LOCAL_INSTANCE
STL namespace.
Concurrency control classes.
Definition: CyclicBarrier.hpp:26
A thread local instance that can be used as a class member instance variable.
Definition: ThreadLocalInstance.hpp:27