aboutsummaryrefslogtreecommitdiff
path: root/dep/src/zthread/MutexImpl.h
blob: 10a9160ce5a69ac5fdf64a8377ca8faf27039a36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
 * Copyright (c) 2005, Eric Crahen
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include "zthread/Exceptions.h"
#include "zthread/Guard.h"

#include "Debug.h"
#include "FastLock.h"
#include "Scheduling.h"

#include <assert.h>
#include <errno.h>

namespace ZThread {


/**
 * @author Eric Crahen <http://www.code-foo.com>
 * @date <2003-07-16T19:52:12-0400>
 * @version 2.2.11
 * @class NullBehavior
 */
class NullBehavior {
protected:

  inline void waiterArrived(ThreadImpl*) {  }

  inline void waiterDeparted(ThreadImpl*) {  }

  inline void ownerAcquired(ThreadImpl*) {  }

  inline void ownerReleased(ThreadImpl*) {  }

};

/**
 * @author Eric Crahen <http://www.code-foo.com>
 * @date <2003-07-16T19:52:12-0400>
 * @version 2.2.11
 * @class MutexImpl
 *
 * The MutexImpl template allows how waiter lists are sorted, and 
 * what actions are taken when a thread interacts with the mutex
 * to be parametized.
 */
template <typename List, typename Behavior> 
class MutexImpl : Behavior {

  //! List of Events that are waiting for notification 
  List _waiters;

  //! Serialize access to this Mutex
  FastLock _lock;

  //! Current owner
  volatile ThreadImpl* _owner;

 public:
  

  /**
   * Create a new MutexImpl
   *
   * @exception Initialization_Exception thrown if resources could not be
   * properly allocated
   */
  MutexImpl() : _owner(0) { }
  
  ~MutexImpl();

  void acquire();
  
  void release();

  bool tryAcquire(unsigned long timeout);

};

  /**
   * Destroy this MutexImpl and release its resources
   */
template<typename List, typename Behavior> 
MutexImpl<List, Behavior>::~MutexImpl() {

#ifndef NDEBUG

    // It is an error to destroy a mutex that has not been released
    if(_owner != 0) { 

      ZTDEBUG("** You are destroying a mutex which was never released. **\n");
      assert(0); // Destroyed mutex while in use

    }

    if(!_waiters.empty()) { 

      ZTDEBUG("** You are destroying a mutex which is blocking %d threads. **\n", _waiters.size());
      assert(0); // Destroyed mutex while in use

    }

#endif

  }


  /**
   * Acquire a lock on the mutex. If this operation succeeds the calling
   * thread holds an exclusive lock on this mutex, otherwise it is blocked 
   * until the lock can be acquired.
   *
   * @exception Deadlock_Exception thrown when the caller attempts to acquire() more
   * than once, If the checking flag is set.
   * @exception Interrupted_Exception thrown when the caller status is interrupted
   * @exception Synchronization_Exception thrown if there is some other error.
   */
template<typename List, typename Behavior> 
void MutexImpl<List, Behavior>::acquire() {

    ThreadImpl* self = ThreadImpl::current();
    Monitor& m = self->getMonitor();

    Monitor::STATE state;

    Guard<FastLock> g1(_lock);
   
    // Deadlock will occur if the current thread is the owner 
    // and there is no entry count.
    if(_owner == self) 
      throw Deadlock_Exception();
    
    // Acquire the lock if it is free and there are no waiting threads
    if(_owner == 0 && _waiters.empty()) {

      _owner = self;

      this->ownerAcquired(self);
      
    }

    // Otherwise, wait for a signal from a thread releasing its
    // ownership of the lock
    else { 
        
      _waiters.insert(self);
      m.acquire();

      this->waiterArrived(self);

      {        
      
        Guard<FastLock, UnlockedScope> g2(g1);
        state = m.wait();
      
      }

      this->waiterDeparted(self);

      m.release();
        
      // Remove from waiter list, regardless of wether release() is called or
      // not. The monitor is sticky, so its possible a state 'stuck' from a
      // previous operation and will leave the wait() w/o release() having
      // been called (e.g. interrupted)
      typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
      if(i != _waiters.end())
        _waiters.erase(i);

      // If awoke due to a notify(), take ownership. 
      switch(state) {
        case Monitor::SIGNALED:

          assert(_owner == 0);
          _owner = self;    

          this->ownerAcquired(self);

          break;
        
        case Monitor::INTERRUPTED:
          throw Interrupted_Exception();
        
        default:
          throw Synchronization_Exception();
      } 
    
    }
  
  }


  /**
   * Acquire a lock on the mutex. If this operation succeeds the calling
   * thread holds an exclusive lock on this mutex. If the lock cannot be
   * obtained before the timeout expires, the caller returns false.
   *
   * @exception Deadlock_Exception thrown when the caller attempts to acquire() more
   * than once, If the checking flag is set.
   * @exception Interrupted_Exception thrown when the caller status is interrupted
   * @exception Synchronization_Exception thrown if there is some other error.
   */
template<typename List, typename Behavior> 
bool MutexImpl<List, Behavior>::tryAcquire(unsigned long timeout) {
  
    ThreadImpl* self = ThreadImpl::current();
    Monitor& m = self->getMonitor();

    Guard<FastLock> g1(_lock);
   
    // Deadlock will occur if the current thread is the owner 
    // and there is no entry count.
    if(_owner == self) 
      throw Deadlock_Exception();

    // Acquire the lock if it is free and there are no waiting threads
    if(_owner == 0 && _waiters.empty()) {

      _owner = self;

      this->ownerAcquired(self);
      
    }

    // Otherwise, wait for a signal from a thread releasing its
    // ownership of the lock
    else {
        
      _waiters.insert(self);
    
      Monitor::STATE state = Monitor::TIMEDOUT;
    
      // Don't bother waiting if the timeout is 0
      if(timeout) {
      
        m.acquire();

        this->waiterArrived(self);
      
        {
        
          Guard<FastLock, UnlockedScope> g2(g1);
          state = m.wait(timeout);
        
        }

        this->waiterDeparted(self);
      
        m.release();
        
      }
    
    
      // Remove from waiter list, regarless of weather release() is called or
      // not. The monitor is sticky, so its possible a state 'stuck' from a
      // previous operation and will leave the wait() w/o release() having
      // been called.
      typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
      if(i != _waiters.end())
        _waiters.erase(i);
    
      // If awoke due to a notify(), take ownership. 
      switch(state) {
        case Monitor::SIGNALED:
        
          assert(0 == _owner);
          _owner = self;

          this->ownerAcquired(self);
        
          break;
        
        case Monitor::INTERRUPTED:
          throw Interrupted_Exception();
        
        case Monitor::TIMEDOUT:
          return false;
        
        default:
          throw Synchronization_Exception();
      } 
    
    }
  
    return true;
  
  }

  /**
   * Release a lock on the mutex. If this operation succeeds the calling
   * thread no longer holds an exclusive lock on this mutex. If there are 
   * waiting threads, one will be selected, assigned ownership and specifically 
   * awakened.
   *
   * @exception InvalidOp_Exception - thrown if an attempt is made to 
   * release a mutex not owned by the calling thread.
   */
template<typename List, typename Behavior> 
void MutexImpl<List, Behavior>::release() {

    ThreadImpl* impl = ThreadImpl::current();

    Guard<FastLock> g1(_lock);
  
    // Make sure the operation is valid
    if(_owner != impl)
      throw InvalidOp_Exception();

    _owner = 0;

    this->ownerReleased(impl);
  
    // Try to find a waiter with a backoff & retry scheme
    for(;;) {
    
      // Go through the list, attempt to notify() a waiter.
      for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
      
        // Try the monitor lock, if it cant be locked skip to the next waiter
        impl = *i;
        Monitor& m = impl->getMonitor();

        if(m.tryAcquire()) {
  
          // If notify() is not sucessful, it is because the wait() has already 
          // been ended (killed/interrupted/notify'd)
          bool woke = m.notify();
          
          m.release();
        
          // Once notify() succeeds, return
          if(woke)
            return;
        
        } else ++i;
      
      }
    
      if(_waiters.empty())
        return;

      { // Backoff and try again
      
        Guard<FastLock, UnlockedScope> g2(g1);
        ThreadImpl::yield();

      }

    }
  
  }

} // namespace ZThread