include/am-thread-utils.h
author David Anderson <danderson@mozilla.com>
Mon Aug 26 23:18:03 2013 -0700 (2013-08-26)
changeset 11 cfe800908837
parent 0 ba3d4abaf3f1
permissions -rw-r--r--
Add tests.
danderson@0
     1
// vim: set sts=8 ts=2 sw=2 tw=99 et:
danderson@0
     2
//
danderson@0
     3
// Copyright (C) 2013, David Anderson and AlliedModders LLC
danderson@0
     4
// All rights reserved.
danderson@0
     5
// 
danderson@0
     6
// Redistribution and use in source and binary forms, with or without
danderson@0
     7
// modification, are permitted provided that the following conditions are met:
danderson@0
     8
// 
danderson@0
     9
//  * Redistributions of source code must retain the above copyright notice, this
danderson@0
    10
//    list of conditions and the following disclaimer.
danderson@0
    11
//  * Redistributions in binary form must reproduce the above copyright notice,
danderson@0
    12
//    this list of conditions and the following disclaimer in the documentation
danderson@0
    13
//    and/or other materials provided with the distribution.
danderson@0
    14
//  * Neither the name of AlliedModders LLC nor the names of its contributors
danderson@0
    15
//    may be used to endorse or promote products derived from this software
danderson@0
    16
//    without specific prior written permission.
danderson@0
    17
//
danderson@0
    18
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
danderson@0
    19
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
danderson@0
    20
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
danderson@0
    21
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
danderson@0
    22
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
danderson@0
    23
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
danderson@0
    24
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
danderson@0
    25
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
danderson@0
    26
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
danderson@0
    27
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
danderson@0
    28
// POSSIBILITY OF SUCH DAMAGE.
danderson@0
    29
danderson@0
    30
#ifndef _include_amtl_threads_
danderson@0
    31
#define _include_amtl_threads_
danderson@0
    32
danderson@0
    33
#include <assert.h>
danderson@0
    34
#if defined(_MSC_VER)
danderson@0
    35
# include <windows.h>
danderson@0
    36
# include <WinBase.h>
danderson@0
    37
#else
danderson@0
    38
# include <pthread.h>
danderson@0
    39
#endif
danderson@0
    40
#include <am-utility.h>
danderson@0
    41
danderson@0
    42
// Thread primitives for SourcePawn.
danderson@0
    43
//
danderson@0
    44
// Linking Requirements:
danderson@0
    45
// 
danderson@0
    46
// OS X: None (-lpthread and -ldl are optional)
danderson@0
    47
// Windows: None
danderson@0
    48
// Linux: -lpthread -lrt required
danderson@0
    49
//
danderson@0
    50
// -- Mutexes --
danderson@0
    51
//
danderson@0
    52
// A Lockable is a mutual exclusion primitive. It can be owned by at most one
danderson@0
    53
// thread at a time, and ownership blocks any other thread from taking taking
danderson@0
    54
// ownership. Ownership must be acquired and released on the same thread.
danderson@0
    55
// Lockables are not re-entrant.
danderson@0
    56
//
danderson@0
    57
// While a few classes support the Lockable interface, the simplest Lockable
danderson@0
    58
// object that can be instantiated is a Mutex.
danderson@0
    59
//
danderson@0
    60
// -- Condition Variables --
danderson@0
    61
//
danderson@0
    62
// A ConditionVariable provides mutually exclusive access based on a
danderson@0
    63
// condition ocurring. CVs provide two capabilities: Wait(), which will block
danderson@0
    64
// until the condition is triggered, and Notify(), which signals any blocking
danderson@0
    65
// thread that the condition has occurred.
danderson@0
    66
//
danderson@0
    67
// Condition variables have an underlying mutex lock. This lock must be
danderson@0
    68
// acquired before calling Wait() or Notify(). It is automatically released
danderson@0
    69
// once Wait begins blocking. This operation is atomic with respect to other
danderson@0
    70
// threads and the mutex. For example, it is not possible for the lock to be
danderson@0
    71
// acquired by another thread in between unlocking and blocking. Since Notify
danderson@0
    72
// also requires the lock to be acquired, there is no risk of an event
danderson@0
    73
// accidentally dissipating into thin air because it was sent before the other
danderson@0
    74
// thread began blocking.
danderson@0
    75
//
danderson@0
    76
// When Wait() returns, the lock is automatically re-acquired. This operation
danderson@0
    77
// is NOT atomic. In between waking up and re-acquiring the lock, another
danderson@0
    78
// thread may steal the lock and issue another event. Applications must
danderson@0
    79
// account for this. For example, a message pump should check that there are
danderson@0
    80
// no messages left to process before blocking again.
danderson@0
    81
//
danderson@0
    82
// Likewise, it is also not defined whether a Signal() will have any effect
danderson@0
    83
// while a thread is not waiting on the monitor. This is yet another reason
danderson@0
    84
// the above paragraph is so important - applications should, under a lock of
danderson@0
    85
// the condition variable - check for state changes before waiting.
danderson@0
    86
//
danderson@0
    87
// -- Threads --
danderson@0
    88
//
danderson@0
    89
// A Thread object, when created, spawns a new thread with the given callback
danderson@0
    90
// (the callbacks must implement IRunnable). Threads have one method of
danderson@0
    91
// interest, Join(), which will block until the thread's execution finishes.
danderson@0
    92
// Deleting a thread object will free any operating system resources associated
danderson@0
    93
// with that thread, if the thread has finished executing.
danderson@0
    94
//
danderson@0
    95
// Threads can fail to spawn; make sure to check Succeeded().
danderson@0
    96
//
danderson@0
    97
danderson@0
    98
namespace ke {
danderson@0
    99
danderson@0
   100
// Abstraction for getting a unique thread identifier. Debug-only.
danderson@0
   101
#if defined(_MSC_VER)
danderson@0
   102
typedef DWORD ThreadId;
danderson@0
   103
danderson@0
   104
static inline ThreadId GetCurrentThreadId()
danderson@0
   105
{
danderson@0
   106
  return ::GetCurrentThreadId();
danderson@0
   107
}
danderson@0
   108
#else
danderson@0
   109
typedef pthread_t ThreadId;
danderson@0
   110
danderson@0
   111
static inline ThreadId GetCurrentThreadId()
danderson@0
   112
{
danderson@0
   113
  return pthread_self();
danderson@0
   114
}
danderson@0
   115
#endif
danderson@0
   116
danderson@0
   117
// Classes which use non-reentrant, same-thread lock/unlock semantics should
danderson@0
   118
// inherit from this and implement DoLock/DoUnlock.
danderson@0
   119
class Lockable
danderson@0
   120
{
danderson@0
   121
 public:
danderson@0
   122
  Lockable()
danderson@0
   123
  {
danderson@0
   124
#if !defined(NDEBUG)
danderson@0
   125
    owner_ = 0;
danderson@0
   126
#endif
danderson@0
   127
  }
danderson@0
   128
  virtual ~Lockable() {
danderson@0
   129
  }
danderson@0
   130
danderson@0
   131
  bool TryLock() {
danderson@0
   132
    if (DoTryLock()) {
danderson@0
   133
      DebugSetLocked();
danderson@0
   134
      return true;
danderson@0
   135
    }
danderson@0
   136
    return false;
danderson@0
   137
  }
danderson@0
   138
danderson@0
   139
  void Lock() {
danderson@0
   140
    assert(Owner() != GetCurrentThreadId());
danderson@0
   141
    DoLock();
danderson@0
   142
    DebugSetLocked();
danderson@0
   143
  }
danderson@0
   144
danderson@0
   145
  void Unlock() {
danderson@0
   146
    assert(Owner() == GetCurrentThreadId());
danderson@0
   147
    DebugSetUnlocked();
danderson@0
   148
    DoUnlock();
danderson@0
   149
  }
danderson@0
   150
danderson@0
   151
  void AssertCurrentThreadOwns() const {
danderson@0
   152
    assert(Owner() == GetCurrentThreadId());
danderson@0
   153
  }
danderson@0
   154
#if !defined(NDEBUG)
danderson@0
   155
  bool Locked() const {
danderson@0
   156
    return owner_ != 0;
danderson@0
   157
  }
danderson@0
   158
  ThreadId Owner() const {
danderson@0
   159
    return owner_;
danderson@0
   160
  }
danderson@0
   161
#endif
danderson@0
   162
danderson@0
   163
  virtual bool DoTryLock() = 0;
danderson@0
   164
  virtual void DoLock() = 0;
danderson@0
   165
  virtual void DoUnlock() = 0;
danderson@0
   166
danderson@0
   167
 protected:
danderson@0
   168
  void DebugSetUnlocked() {
danderson@0
   169
#if !defined(NDEBUG)
danderson@0
   170
    owner_ = 0;
danderson@0
   171
#endif
danderson@0
   172
  }
danderson@0
   173
  void DebugSetLocked() {
danderson@0
   174
#if !defined(NDEBUG)
danderson@0
   175
    owner_ = GetCurrentThreadId();
danderson@0
   176
#endif
danderson@0
   177
  }
danderson@0
   178
danderson@0
   179
 protected:
danderson@0
   180
#if !defined(NDEBUG)
danderson@0
   181
  ThreadId owner_;
danderson@0
   182
#endif
danderson@0
   183
};
danderson@0
   184
danderson@0
   185
// RAII for automatically locking and unlocking an object.
danderson@0
   186
class AutoLock
danderson@0
   187
{
danderson@0
   188
 public:
danderson@0
   189
  AutoLock(Lockable *lock)
danderson@0
   190
   : lock_(lock)
danderson@0
   191
  {
danderson@0
   192
    lock_->Lock();
danderson@0
   193
  }
danderson@0
   194
  ~AutoLock() {
danderson@0
   195
    lock_->Unlock();
danderson@0
   196
  }
danderson@0
   197
danderson@0
   198
 private:
danderson@0
   199
  Lockable *lock_;
danderson@0
   200
};
danderson@0
   201
danderson@0
   202
class AutoTryLock
danderson@0
   203
{
danderson@0
   204
 public:
danderson@0
   205
  AutoTryLock(Lockable *lock)
danderson@0
   206
  {
danderson@0
   207
    lock_ = lock->TryLock() ? lock : NULL;
danderson@0
   208
  }
danderson@0
   209
  ~AutoTryLock() {
danderson@0
   210
    if (lock_)
danderson@0
   211
      lock_->Unlock();
danderson@0
   212
  }
danderson@0
   213
danderson@0
   214
 private:
danderson@0
   215
  Lockable *lock_;
danderson@0
   216
};
danderson@0
   217
danderson@0
   218
// RAII for automatically unlocking and relocking an object.
danderson@0
   219
class AutoUnlock
danderson@0
   220
{
danderson@0
   221
 public:
danderson@0
   222
  AutoUnlock(Lockable *lock)
danderson@0
   223
   : lock_(lock)
danderson@0
   224
  {
danderson@0
   225
    lock_->Unlock();
danderson@0
   226
  }
danderson@0
   227
  ~AutoUnlock() {
danderson@0
   228
    lock_->Lock();
danderson@0
   229
  }
danderson@0
   230
danderson@0
   231
 private:
danderson@0
   232
  Lockable *lock_;
danderson@0
   233
};
danderson@0
   234
danderson@0
   235
enum WaitResult {
danderson@0
   236
  // Woke up because something happened.
danderson@0
   237
  Wait_Signaled,
danderson@0
   238
danderson@0
   239
  // Woke up because nothing happened and a timeout was specified.
danderson@0
   240
  Wait_Timeout,
danderson@0
   241
danderson@0
   242
  // Woke up, but because of an error.
danderson@0
   243
  Wait_Error
danderson@0
   244
};
danderson@0
   245
danderson@0
   246
// This must be implemented in order to spawn a new thread.
danderson@0
   247
class IRunnable
danderson@0
   248
{
danderson@0
   249
 public:
danderson@0
   250
  virtual ~IRunnable() {
danderson@0
   251
  }
danderson@0
   252
danderson@0
   253
  virtual void Run() = 0;
danderson@0
   254
};
danderson@0
   255
danderson@0
   256
} // namespace ke
danderson@0
   257
danderson@0
   258
// Include the actual thread implementations.
danderson@0
   259
#if defined(_MSC_VER)
danderson@0
   260
# include "am-thread-windows.h"
danderson@0
   261
#else
danderson@0
   262
# include "am-thread-posix.h"
danderson@0
   263
#endif
danderson@0
   264
danderson@0
   265
#endif // _include_amtl_threads_