tlds
Transactional Operations for Linked Data Structures
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
lockkey.h
Go to the documentation of this file.
1 #ifndef LOCKKEY_H
2 #define LOCKKEY_H
3 
4 #include <tbb/concurrent_hash_map.h>
5 #include <mutex>
6 #include <unordered_set>
7 #include <chrono>
8 
9 class LockKey
10 {
11  typedef std::recursive_timed_mutex LockType;
12  typedef tbb::concurrent_hash_map<uint32_t, LockType*> LockMap;
13  typedef std::unordered_set<LockType*> LockSet;
14 
15 public:
17  {}
18 
20  {
21  for(LockMap::iterator it = m_lockMap.begin(); it != m_lockMap.end(); ++it)
22  {
23  delete it->second;
24  }
25  }
26 
27  void Init()
28  {
29  m_lockSet = new LockSet;
30  }
31 
32  void Uninit()
33  {
34  delete m_lockSet;
35  }
36 
37  bool Lock(uint32_t key)
38  {
39  LockMap::accessor acc;
40  LockType* lock = NULL;
41 
42  if(m_lockMap.insert(acc, key))
43  {
44  lock = new LockType;
45  acc->second = lock;
46  }
47  else
48  {
49  lock = acc->second;
50  }
51 
52  std::pair<LockSet::iterator, bool> ret = m_lockSet->insert(lock);
53  if(ret.second)
54  {
55  if(lock->try_lock_for(std::chrono::milliseconds(100)))
56  {
57  return true;
58  }
59  else
60  {
61  m_lockSet->erase(lock);
62  }
63  }
64 
65  return false;
66  }
67 
68  void Unlock()
69  {
70  for(LockSet::iterator it = m_lockSet->begin(); it != m_lockSet->end(); ++it)
71  {
72  (*it)->unlock();
73  }
74 
75  m_lockSet->clear();
76  }
77 
78 private:
80  static __thread LockSet* m_lockSet;
81 };
82 
83 #endif /* end of include guard: LOCKKEY_H */
void Unlock()
Definition: lockkey.h:68
static __thread LockSet * m_lockSet
Definition: lockkey.h:80
LockMap m_lockMap
Definition: lockkey.h:79
void Init()
Definition: lockkey.h:27
std::recursive_timed_mutex LockType
Definition: lockkey.h:11
bool Lock(uint32_t key)
Definition: lockkey.h:37
bool ret
Definition: stmskip.cc:242
std::unordered_set< LockType * > LockSet
Definition: lockkey.h:13
~LockKey()
Definition: lockkey.h:19
void Uninit()
Definition: lockkey.h:32
Definition: lockkey.h:9
LockKey()
Definition: lockkey.h:16
tbb::concurrent_hash_map< uint32_t, LockType * > LockMap
Definition: lockkey.h:12