source: src/CodePatterns/AtomicInstance_impl.hpp@ 039e15

Last change on this file since 039e15 was 039e15, checked in by Frederik Heber <heber@…>, 9 years ago

Added AtomicInstance as a mutex-locked wrapper around a given entity.

  • this should help in multi-threaded codes to prevent accessing the entity from more than one thread at once: Lock the entity by accessing it within a scope while wrapped in AtomicInstance.
  • Property mode set to 100644
File size: 1.6 KB
Line 
1/*
2 * AtomicInstance_impl.hpp
3 *
4 * Created on: Apr 26, 2016
5 * Author: heber
6 */
7
8
9#ifndef ATOMICINSTANCE_IMPL_HPP_
10#define ATOMICINSTANCE_IMPL_HPP_
11
12// include config.h
13#ifdef HAVE_CONFIG_H
14#include <config.h>
15#endif
16
17#include "CodePatterns/Assert.hpp"
18
19#include "AtomicInstance.hpp"
20
21template<class T> boost::mutex AtomicInstance< T >::atomicLock;
22
23template <class T>
24AtomicInstance<T>::AtomicInstance(T* _content) :
25 content(_content)
26{
27 if (content != NULL)
28 AtomicInstance<T>::atomicLock.lock();
29}
30
31template <class T>
32AtomicInstance<T>::AtomicInstance() :
33 content(NULL)
34{
35}
36
37template <class T>
38AtomicInstance<T>::~AtomicInstance()
39{
40 if (content != NULL)
41 AtomicInstance<T>::atomicLock.unlock();
42}
43
44template <class T>
45T& AtomicInstance<T>::operator*()
46{ return *content;}
47
48template <class T>
49const T& AtomicInstance<T>::operator*() const
50{ return *content;}
51
52template <class T>
53AtomicInstance<T>& AtomicInstance<T>::operator=(const AtomicInstance<T>& rhs)
54{
55 if (this != &rhs) {
56 this->content = rhs.content;
57 const_cast<AtomicInstance<T>&>(rhs).content = NULL;
58 }
59 return *this;
60}
61
62template <class T>
63AtomicInstance<T>::AtomicInstance(AtomicInstance<T>& rhs) :
64 content(rhs.content)
65{
66 // check for self-copy
67 if (this != &rhs)
68 rhs.content = NULL;
69}
70
71template <class T>
72AtomicInstance<T>::AtomicInstance(const AtomicInstance<T>& rhs) :
73 content(rhs.content)
74{
75 // check for self-copy
76 ASSERT (this != &rhs,
77 "AtomicInstance<T>::AtomicInstance() - self-assignment not allowed for rhs copy.");
78 const_cast<AtomicInstance<T>&>(rhs).content = NULL;
79}
80
81#endif /* ATOMICINSTANCE_IMPL_HPP_ */
Note: See TracBrowser for help on using the repository browser.