NVIDIA Iray: Math API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
lock.h
Go to the documentation of this file.
1 //*****************************************************************************
2 // Copyright 1986, 2014 NVIDIA Corporation. All rights reserved.
3 //*****************************************************************************
9 //*****************************************************************************
10 
11 #ifndef MI_BASE_LOCK_H
12 #define MI_BASE_LOCK_H
13 
14 #include <mi/base/config.h>
15 
16 #ifndef MI_PLATFORM_WINDOWS
17 #include <pthread.h>
18 #else
19 #include <mi/base/miwindows.h>
20 #endif
21 
22 namespace mi {
23 
24 namespace base {
25 
37 // On some operating systems the name is different.
38 #ifndef PTHREAD_MUTEX_ERRORCHECK
39 #define PTHREAD_MUTEX_ERRORCHECK PTHREAD_MUTEX_ERRORCHECK_NP
40 #endif
41 
43 class Lock
44 {
45 
46 public:
47 
49 #ifndef MI_PLATFORM_WINDOWS
50  inline Lock() { pthread_mutex_init(&m_mutex,NULL); };
51 #else
52  inline Lock() { InitializeCriticalSection(&m_critical_section); };
53 #endif
54 
56 #ifndef MI_PLATFORM_WINDOWS
57  inline ~Lock() { pthread_mutex_destroy(&m_mutex); };
58 #else
59  inline ~Lock() { DeleteCriticalSection(&m_critical_section); };
60 #endif
61 
63  class Block {
64 
65  public:
66 
71  explicit Block(Lock* lock = 0);
72 
76  ~Block();
77 
84  void set(Lock* lock);
85 
89  void release();
90 
91  private:
92 
93  // The lock associated with this helper class.
94  Lock* m_lock;
95  };
96 
97 protected:
98 
100 #ifndef MI_PLATFORM_WINDOWS
101  void lock() { pthread_mutex_lock(&m_mutex); };
102 #else
103  void lock() { EnterCriticalSection(&m_critical_section); };
104 #endif
105 
107 #ifndef MI_PLATFORM_WINDOWS
108  void unlock() { pthread_mutex_unlock(&m_mutex); };
109 #else
110  void unlock() { LeaveCriticalSection(&m_critical_section); };
111 #endif
112 
113 private:
114 
115  // This class is non-copyable.
116  Lock(Lock const &);
117 
118  // This class is non-assignable.
119  Lock& operator= (Lock const &);
120 
121  // The mutex implementing the lock.
122 #ifndef MI_PLATFORM_WINDOWS
123  pthread_mutex_t m_mutex;
124 #else
125  CRITICAL_SECTION m_critical_section;
126 #endif
127 };
128 
130 {
131  m_lock = lock;
132  if (m_lock)
133  m_lock->lock();
134 }
135 
137 {
138  release();
139 }
140 
142 {
143  if (m_lock)
144  m_lock->unlock();
145  m_lock = lock;
146  if (m_lock)
147  m_lock->lock();
148 }
149 
150 inline void Lock::Block::release()
151 {
152  if (m_lock)
153  m_lock->unlock();
154  m_lock = 0;
155 }
156  // end group mi_base_threads
158 
159 } // namespace base
160 } // namespace mi
161 
162 #endif // MI_BASE_LOCK_H