|
1
|
1 #pragma once
|
|
|
2 namespace pfc {
|
|
|
3
|
|
|
4 template<typename obj_t_, typename mutex_t_>
|
|
|
5 struct threadSafeObjCommon {
|
|
|
6 typedef mutex_t_ mutex_t;
|
|
|
7 typedef obj_t_ obj_t;
|
|
|
8 template<typename ... arg_t> threadSafeObjCommon( arg_t && ... arg ) : m_obj(std::forward<arg_t>(arg) ... ) {}
|
|
|
9 mutex_t m_mutex;
|
|
|
10 obj_t m_obj;
|
|
|
11 };
|
|
|
12
|
|
|
13 template<typename common_t>
|
|
|
14 class threadSafeObjLock {
|
|
|
15 typedef threadSafeObjLock<common_t> self_t;
|
|
|
16 common_t & m_common;
|
|
|
17 public:
|
|
|
18 typename common_t::obj_t & operator*() { return m_common.m_obj; }
|
|
|
19 typename common_t::obj_t * operator->() { return & m_common.m_obj; }
|
|
|
20
|
|
|
21 threadSafeObjLock( common_t & arg ) : m_common(arg) { m_common.m_mutex.lock(); }
|
|
|
22 ~threadSafeObjLock( ) { m_common.m_mutex.unlock(); }
|
|
|
23 threadSafeObjLock( const self_t & ) = delete;
|
|
|
24 void operator=( const self_t & ) = delete;
|
|
|
25 };
|
|
|
26
|
|
|
27 template<typename obj_t, typename mutex_t = pfc::mutex>
|
|
|
28 class threadSafeObj {
|
|
|
29 typedef threadSafeObjCommon<obj_t, mutex_t> common_t;
|
|
|
30 typedef threadSafeObjLock<common_t> lock_t;
|
|
|
31 common_t m_common;
|
|
|
32 public:
|
|
|
33 template<typename ... arg_t>
|
|
|
34 threadSafeObj( arg_t && ... arg ) : m_common( std::forward<arg_t>(arg) ... ) {}
|
|
|
35
|
|
|
36 lock_t get() { return lock_t(m_common); }
|
|
|
37 };
|
|
|
38
|
|
|
39 }
|