aboutsummaryrefslogtreecommitdiff
path: root/dep/src/zthread/ThreadImpl.cxx
blob: c7c22883b5efa9a00c5ac6bbc1e7b320226ce8f4 (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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
 * 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 "Debug.h"

#include "zthread/Runnable.h"
#include "ThreadImpl.h"
#include "ThreadQueue.h"
#include "DeferredInterruptionScope.h"

#include <assert.h>

namespace ZThread {

  TSS<ThreadImpl*> ThreadImpl::_threadMap;

  namespace {
  
    class Launcher : public Runnable {
      
      ThreadImpl* x;
      ThreadImpl* y;
      Task z;
      
    public:
      
      Launcher(ThreadImpl* a, ThreadImpl* b, const Task& c) : x(a), y(b), z(c) {}
      
      void run() {      
        y->dispatch(x,y,z);      
      }
            
    };
    
  }

  ThreadImpl::ThreadImpl() 
    : _state(State::REFERENCE), _priority(Medium), _autoCancel(false) {
    
    ZTDEBUG("Reference thread created.\n");
    
  }

  ThreadImpl::ThreadImpl(const Task& task, bool autoCancel) 
    : _state(State::IDLE), _priority(Medium), _autoCancel(autoCancel) {
    
    ZTDEBUG("User thread created.\n");

    start(task);

  }
  
  
  ThreadImpl::~ThreadImpl() {
    
    _tls.clear();

    if(isActive()) {
      
      ZTDEBUG("You are destroying an executing thread!\n");
      abort();
      
    }
    
    ZTDEBUG("Thread destroyed.\n");
    
  }
  
  Monitor& ThreadImpl::getMonitor() {
    return _monitor;
  }
  
  void ThreadImpl::cancel(bool autoCancel) {
    if(!autoCancel || _autoCancel) 
      _monitor.cancel(); 
  }
  
  bool ThreadImpl::interrupt() { 
    return _monitor.interrupt(); 
  }
  
  bool ThreadImpl::isInterrupted() {
    return _monitor.isInterrupted();
  }
  
  bool ThreadImpl::isCanceled() {
    return _monitor.isCanceled();
  }

  Priority ThreadImpl::getPriority() const {
    return _priority;  
  }
  
 

  bool ThreadImpl::isReference() {
    return _state.isReference();
  }
  
  /**
   * Join the thread, blocking the caller until it is interrupted or until
   * the thread represented by this object exits.
   *
   * Reference threads are not under the control of ZThreads and cannot be
   * joined.
   */
  bool ThreadImpl::join(unsigned long timeout) {
     
    // Serial access to this ThreadImpl's state
    Guard<Monitor> g1(_monitor);
  
    // Make sure a thread is not trying to join() itself.
    if(ThreadOps::isCurrent(this))
      throw Deadlock_Exception("Cannot join self.");
    
    // Reference threads can't be joined. 
    if(_state.isReference())
      throw InvalidOp_Exception("Can not join this thread.");
    
    /*  
        
    TODO: Insert cyclic join check. 
    
    */
    
    // If the task has not completed yet, wait for completion
    if(!_state.isJoined()) {
      
      // Add the current thread to the joiner list
      ThreadImpl* impl = current();
      _joiners.push_back(impl);

      Monitor::STATE result;

      { // Release this ThreadImpl's lock while the joiner sleeps

        _monitor.release();  
        Guard<Monitor> g3(impl->getMonitor());
 
        result = impl->_monitor.wait(timeout);
 
        _monitor.acquire();
         
      }
       
      // Update the joiner list
      List::iterator i = std::find(_joiners.begin(), _joiners.end(), impl);
      if(i != _joiners.end())
        _joiners.erase(i);
      
      
      switch(result) {
        
        case Monitor::TIMEDOUT:
          return false;
          
        case Monitor::INTERRUPTED:
          throw Interrupted_Exception();
          
        default:
          break;
          
      }
      
    }

    return true;
    
  }
  

  /**
   * Translate the priority into a pthread value, and update the thread priority.
   *
   * This is not available on all platforms, and probably works differently 
   * the platforms that do support it. Pthreads does not have very portable 
   * priority support as far I am aware.
   *
   * If SCHED_OTHER is not supported priority values are still set but  
   * dont not actually in affect anything.
   *
   * @param prio PRIORITY value
   *
   * @exception Killed_Exception thrown by KILLED threads.
   * @exception InvalidOp_Exception thrown by IDLE, JOINING or JOINED threads.
   */
  void ThreadImpl::setPriority(Priority p) {
    
    Guard<Monitor> g(_monitor);
    
    // Only set the native priority when the thread is running
    if(_state.isRunning())
      ThreadOps::setPriority(this, p);
    
    _priority = p;
    
  }
  
  
  /**
   * Test the state Monitor of this thread to determine if the thread
   * is an active thread created by zthreads.
   *
   * @return bool indicating the activity of the thread.
   */
  bool ThreadImpl::isActive() {
    
    Guard<Monitor> g(_monitor);
    return _state.isRunning();
    
  }
  
  
  /**
   * Get a reference to an implmenetation that maps to the current thread.
   * Accomplished by checking the TLS map. This will always return a valid
   * ThreadImpl instance.
   *
   * @return ThreadImpl* current implementation that maps to the
   * executing thread.
   */ 
  ThreadImpl* ThreadImpl::current() {
    
    // Get the ThreadImpl previously mapped onto the executing thread.
    ThreadImpl* impl = _threadMap.get();
    
    // Create a reference thread for any threads that have been 'discovered'
    // because they are not created by ZThreads.
    if(impl == 0) { 
      
      // Create a ThreadImpl to represent this thread. 
      impl = new ThreadImpl();
      impl->_state.setReference();
      
      ThreadOps::activate(impl);
      
      // Map a reference thread and insert it into the queue
      _threadMap.set(impl);
      
      ThreadQueue::instance()->insertReferenceThread(impl);
      
    }
    
    assert(impl != 0);
    return impl;
    
  }
  
  /**
   * Make current thread sleep for the given number of milliseconds.
   * This sleep can be interrupt()ed.
   * 
   * @param ms timeout for the sleep.
   *
   * @post the calling thread is blocked by waiting on the internal condition
   * variable. This can be signaled in the monitor of an interrupt
   */
  void ThreadImpl::sleep(unsigned long ms) {
    
    // Make sleep()ing for 0 milliseconds equivalent to a yield.
    if(ms == 0) {
      
      yield();
      return;
      
    }
    
    // Get the monitor for the current thread
    Monitor& monitor = current()->getMonitor();
    
    // Acquire that threads Monitor with a Guard
    Guard<Monitor> g(monitor);
    
    for(;;) {
      
      switch(monitor.wait(ms)) {
        
        case Monitor::INTERRUPTED:
          throw Interrupted_Exception();
          
        default:
          return;
          
      }
      
    }
    
  }
  
  
  /**
   * Yield the current timeslice to another thread. 
   * If sched_yield() is available it is used. 
   * Otherwise, the state Monitor for this thread is used to simiulate a
   * yield by blocking for 1  millisecond, which should give the 
   * scheduler a chance to schedule another thread.
   */
  void ThreadImpl::yield() {
    
    // Try to yield with the native operation. If it fails, then 
    // simulate with a short wait() on the monitor.
    if(!ThreadOps::yield()) {
      
      // Get the monitor for the current thread
      Monitor& monitor = current()->getMonitor();
      
      // Attempt a wait().
      Guard<Monitor> g(monitor);    
      monitor.wait(1);
      
    }
    
  }

  void ThreadImpl::start(const Task& task) {

    Guard<Monitor> g1(_monitor);

    // A Thread must be idle in order to be eligable to run a task.
    if(!_state.isIdle())
      throw InvalidOp_Exception("Thread is not idle.");
  
    _state.setRunning();
  
    // Spawn a new thread, blocking the parent (current) thread until
    // the child starts.

    ThreadImpl* parent = current();
    Launcher launch(parent, this, task);

    // Attempt to start the child thread
    Guard<Monitor> g2(parent->_monitor);

    if(!spawn(&launch)) {

      // Return to the idle state & report the error if it doesn't work out.
      _state.setIdle();    
      throw Synchronization_Exception();    


    }

    // Wait, uninterruptably, for the child's signal. The parent thread
    // still can be interrupted and killed; it just won't take effect 
    // until the child has started.

    Guard<Monitor, DeferredInterruptionScope> g3(parent->_monitor);

    if(parent->_monitor.wait() != Monitor::SIGNALED) {
      assert(0);
    }
  

  }


  void ThreadImpl::dispatch(ThreadImpl* parent, ThreadImpl* impl, Task task) {

    // Map the implementation object onto the running thread.
    _threadMap.set(impl);

    // Update the reference count on a ThreadImpl before the 'Thread' 
    // that owns it can go out of scope (by signaling the parent)
    impl->addReference();

    // Update the priority of the thread
    if(parent->_state.isReference()) 
      ThreadOps::setPriority(impl, 
                             parent->_state.isReference() ? impl->_priority : parent->_priority);

    // Inherit ThreadLocal values from the parent
    typedef ThreadLocalMap::const_iterator It;

    for(It i = parent->getThreadLocalMap().begin(); i != parent->getThreadLocalMap().end(); ++i) 
      if( (i->second)->isInheritable() )
        impl->getThreadLocalMap()[ i->first ] = (i->second)->clone();
    
    // Insert a user-thread mapping 
    ThreadQueue::instance()->insertUserThread(impl);
    // Wake the parent once the thread is setup
    parent->_monitor.notify();

    ZTDEBUG("Thread starting...\n");

    // not catch exceptions, let program terminate
    //try {
    
      task->run();

    //} catch(...) {

      // Result of running a task that threw an exception.
    //  ZTDEBUG("The task has thrown an unhandled exception\n");
	  //assert(0); // UQ1: Go to debugger...
    
    //}

    ZTDEBUG("Thread joining...\n"); 
    
    { // Update the state of the thread
    
      Guard<Monitor> g(impl->_monitor);
      impl->_state.setJoined();
    
      // Wake the joiners that will be easy to join first
      for(List::iterator i = impl->_joiners.begin(); i != impl->_joiners.end();) {
      
        ThreadImpl* joiner = *i;
        Monitor& m = joiner->getMonitor();

        if(m.tryAcquire()) {
  
          m.notify();
          m.release();   
       
          i = impl->_joiners.erase(i);

        } else
          ++i;

      } 

      // Wake the joiners that might take a while next
      for(List::iterator i = impl->_joiners.begin(); i != impl->_joiners.end(); ++i) {
      
        ThreadImpl* joiner = *i;
        Monitor& m = joiner->getMonitor();

        m.acquire();
        m.notify();
        m.release();   
       
      }
      
    }

    ZTDEBUG("Thread exiting...\n"); 

    // Insert a pending-thread mapping, allowing the resources to be reclaimed 
    ThreadQueue::instance()->insertPendingThread(impl);

    // Cleanup ThreadLocal values
    impl->getThreadLocalMap().clear();

    // Update the reference count allowing it to be destroyed 
    impl->delReference();

  }


} // namespace ZThread