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