nuclear@1: /************************************************************************************ nuclear@1: nuclear@1: PublicHeader: None nuclear@1: Filename : OVR_Threads.h nuclear@1: Content : Contains thread-related (safe) functionality nuclear@1: Created : September 19, 2012 nuclear@1: Notes : nuclear@1: nuclear@1: Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. nuclear@1: nuclear@1: Use of this software is subject to the terms of the Oculus license nuclear@1: agreement provided at the time of installation or download, or which nuclear@1: otherwise accompanies this software in either electronic or hard copy form. nuclear@1: nuclear@1: ************************************************************************************/ nuclear@1: #ifndef OVR_Threads_h nuclear@1: #define OVR_Threads_h nuclear@1: nuclear@1: #include "OVR_Types.h" nuclear@1: #include "OVR_Atomic.h" nuclear@1: #include "OVR_RefCount.h" nuclear@1: #include "OVR_Array.h" nuclear@1: nuclear@1: // Defines the infinite wait delay timeout nuclear@1: #define OVR_WAIT_INFINITE 0xFFFFFFFF nuclear@1: nuclear@1: // To be defined in the project configuration options nuclear@1: #ifdef OVR_ENABLE_THREADS nuclear@1: nuclear@1: nuclear@1: namespace OVR { nuclear@1: nuclear@1: //----------------------------------------------------------------------------------- nuclear@1: // ****** Declared classes nuclear@1: nuclear@1: // Declared with thread support only nuclear@1: class Mutex; nuclear@1: class WaitCondition; nuclear@1: class Event; nuclear@1: // Implementation forward declarations nuclear@1: class MutexImpl; nuclear@1: class WaitConditionImpl; nuclear@1: nuclear@1: nuclear@1: nuclear@1: //----------------------------------------------------------------------------------- nuclear@1: // ***** Mutex nuclear@1: nuclear@1: // Mutex class represents a system Mutex synchronization object that provides access nuclear@1: // serialization between different threads, allowing one thread mutually exclusive access nuclear@1: // to a resource. Mutex is more heavy-weight then Lock, but supports WaitCondition. nuclear@1: nuclear@1: class Mutex nuclear@1: { nuclear@1: friend class WaitConditionImpl; nuclear@1: friend class MutexImpl; nuclear@1: nuclear@1: MutexImpl *pImpl; nuclear@1: nuclear@1: public: nuclear@1: // Constructor/destructor nuclear@1: Mutex(bool recursive = 1); nuclear@1: ~Mutex(); nuclear@1: nuclear@1: // Locking functions nuclear@1: void DoLock(); nuclear@1: bool TryLock(); nuclear@1: void Unlock(); nuclear@1: nuclear@1: // Returns 1 if the mutes is currently locked by another thread nuclear@1: // Returns 0 if the mutex is not locked by another thread, and can therefore be acquired. nuclear@1: bool IsLockedByAnotherThread(); nuclear@1: nuclear@1: // Locker class; Used for automatic locking of a mutex withing scope nuclear@1: class Locker nuclear@1: { nuclear@1: public: nuclear@1: Mutex *pMutex; nuclear@1: Locker(Mutex *pmutex) nuclear@1: { pMutex = pmutex; pMutex->DoLock(); } nuclear@1: ~Locker() nuclear@1: { pMutex->Unlock(); } nuclear@1: }; nuclear@1: }; nuclear@1: nuclear@1: nuclear@1: //----------------------------------------------------------------------------------- nuclear@1: // ***** WaitCondition nuclear@1: nuclear@1: /* nuclear@1: WaitCondition is a synchronization primitive that can be used to implement what is known as a monitor. nuclear@1: Dependent threads wait on a wait condition by calling Wait(), and get woken up by other threads that nuclear@1: call Notify() or NotifyAll(). nuclear@1: nuclear@1: The unique feature of this class is that it provides an atomic way of first releasing a Mutex, and then nuclear@1: starting a wait on a wait condition. If both the mutex and the wait condition are associated with the same nuclear@1: resource, this ensures that any condition checked for while the mutex was locked does not change before nuclear@1: the wait on the condition is actually initiated. nuclear@1: */ nuclear@1: nuclear@1: class WaitCondition nuclear@1: { nuclear@1: friend class WaitConditionImpl; nuclear@1: // Internal implementation structure nuclear@1: WaitConditionImpl *pImpl; nuclear@1: nuclear@1: public: nuclear@1: // Constructor/destructor nuclear@1: WaitCondition(); nuclear@1: ~WaitCondition(); nuclear@1: nuclear@1: // Release mutex and wait for condition. The mutex is re-aquired after the wait. nuclear@1: // Delay is specified in milliseconds (1/1000 of a second). nuclear@1: bool Wait(Mutex *pmutex, unsigned delay = OVR_WAIT_INFINITE); nuclear@1: nuclear@1: // Notify a condition, releasing at one object waiting nuclear@1: void Notify(); nuclear@1: // Notify a condition, releasing all objects waiting nuclear@1: void NotifyAll(); nuclear@1: }; nuclear@1: nuclear@1: nuclear@1: //----------------------------------------------------------------------------------- nuclear@1: // ***** Event nuclear@1: nuclear@1: // Event is a wait-able synchronization object similar to Windows event. nuclear@1: // Event can be waited on until it's signaled by another thread calling nuclear@1: // either SetEvent or PulseEvent. nuclear@1: nuclear@1: class Event nuclear@1: { nuclear@1: // Event state, its mutex and the wait condition nuclear@1: volatile bool State; nuclear@1: volatile bool Temporary; nuclear@1: mutable Mutex StateMutex; nuclear@1: WaitCondition StateWaitCondition; nuclear@1: nuclear@1: void updateState(bool newState, bool newTemp, bool mustNotify); nuclear@1: nuclear@1: public: nuclear@1: Event(bool setInitially = 0) : State(setInitially), Temporary(false) { } nuclear@1: ~Event() { } nuclear@1: nuclear@1: // Wait on an event condition until it is set nuclear@1: // Delay is specified in milliseconds (1/1000 of a second). nuclear@1: bool Wait(unsigned delay = OVR_WAIT_INFINITE); nuclear@1: nuclear@1: // Set an event, releasing objects waiting on it nuclear@1: void SetEvent() nuclear@1: { updateState(true, false, true); } nuclear@1: nuclear@1: // Reset an event, un-signaling it nuclear@1: void ResetEvent() nuclear@1: { updateState(false, false, false); } nuclear@1: nuclear@1: // Set and then reset an event once a waiter is released. nuclear@1: // If threads are already waiting, they will be notified and released nuclear@1: // If threads are not waiting, the event is set until the first thread comes in nuclear@1: void PulseEvent() nuclear@1: { updateState(true, true, true); } nuclear@1: }; nuclear@1: nuclear@1: nuclear@1: //----------------------------------------------------------------------------------- nuclear@1: // ***** Thread class nuclear@1: nuclear@1: // ThreadId uniquely identifies a thread; returned by GetCurrentThreadId() and nuclear@1: // Thread::GetThreadId. nuclear@1: typedef void* ThreadId; nuclear@1: nuclear@1: nuclear@1: // *** Thread flags nuclear@1: nuclear@1: // Indicates that the thread is has been started, i.e. Start method has been called, and threads nuclear@1: // OnExit() method has not yet been called/returned. nuclear@1: #define OVR_THREAD_STARTED 0x01 nuclear@1: // This flag is set once the thread has ran, and finished. nuclear@1: #define OVR_THREAD_FINISHED 0x02 nuclear@1: // This flag is set temporarily if this thread was started suspended. It is used internally. nuclear@1: #define OVR_THREAD_START_SUSPENDED 0x08 nuclear@1: // This flag is used to ask a thread to exit. Message driven threads will usually check this flag nuclear@1: // and finish once it is set. nuclear@1: #define OVR_THREAD_EXIT 0x10 nuclear@1: nuclear@1: nuclear@1: class Thread : public RefCountBase nuclear@1: { // NOTE: Waitable must be the first base since it implements RefCountImpl. nuclear@1: nuclear@1: public: nuclear@1: nuclear@1: // *** Callback functions, can be used instead of overriding Run nuclear@1: nuclear@1: // Run function prototypes. nuclear@1: // Thread function and user handle passed to it, executed by the default nuclear@1: // Thread::Run implementation if not null. nuclear@1: typedef int (*ThreadFn)(Thread *pthread, void* h); nuclear@1: nuclear@1: // Thread ThreadFunction1 is executed if not 0, otherwise ThreadFunction2 is tried nuclear@1: ThreadFn ThreadFunction; nuclear@1: // User handle passes to a thread nuclear@1: void* UserHandle; nuclear@1: nuclear@1: // Thread state to start a thread with nuclear@1: enum ThreadState nuclear@1: { nuclear@1: NotRunning = 0, nuclear@1: Running = 1, nuclear@1: Suspended = 2 nuclear@1: }; nuclear@1: nuclear@1: // Thread priority nuclear@1: enum ThreadPriority nuclear@1: { nuclear@1: CriticalPriority, nuclear@1: HighestPriority, nuclear@1: AboveNormalPriority, nuclear@1: NormalPriority, nuclear@1: BelowNormalPriority, nuclear@1: LowestPriority, nuclear@1: IdlePriority, nuclear@1: }; nuclear@1: nuclear@1: // Thread constructor parameters nuclear@1: struct CreateParams nuclear@1: { nuclear@1: CreateParams(ThreadFn func = 0, void* hand = 0, UPInt ssize = 128 * 1024, nuclear@1: int proc = -1, ThreadState state = NotRunning, ThreadPriority prior = NormalPriority) nuclear@1: : threadFunction(func), userHandle(hand), stackSize(ssize), nuclear@1: processor(proc), initialState(state), priority(prior) {} nuclear@1: ThreadFn threadFunction; // Thread function nuclear@1: void* userHandle; // User handle passes to a thread nuclear@1: UPInt stackSize; // Thread stack size nuclear@1: int processor; // Thread hardware processor nuclear@1: ThreadState initialState; // nuclear@1: ThreadPriority priority; // Thread priority nuclear@1: }; nuclear@1: nuclear@1: // *** Constructors nuclear@1: nuclear@1: // A default constructor always creates a thread in NotRunning state, because nuclear@1: // the derived class has not yet been initialized. The derived class can call Start explicitly. nuclear@1: // "processor" parameter specifies which hardware processor this thread will be run on. nuclear@1: // -1 means OS decides this. Implemented only on Win32 nuclear@1: Thread(UPInt stackSize = 128 * 1024, int processor = -1); nuclear@1: // Constructors that initialize the thread with a pointer to function. nuclear@1: // An option to start a thread is available, but it should not be used if classes are derived from Thread. nuclear@1: // "processor" parameter specifies which hardware processor this thread will be run on. nuclear@1: // -1 means OS decides this. Implemented only on Win32 nuclear@1: Thread(ThreadFn threadFunction, void* userHandle = 0, UPInt stackSize = 128 * 1024, nuclear@1: int processor = -1, ThreadState initialState = NotRunning); nuclear@1: // Constructors that initialize the thread with a create parameters structure. nuclear@1: explicit Thread(const CreateParams& params); nuclear@1: nuclear@1: // Destructor. nuclear@1: virtual ~Thread(); nuclear@1: nuclear@1: // Waits for all Threads to finish; should be called only from the root nuclear@1: // application thread. Once this function returns, we know that all other nuclear@1: // thread's references to Thread object have been released. nuclear@1: static void OVR_CDECL FinishAllThreads(); nuclear@1: nuclear@1: nuclear@1: // *** Overridable Run function for thread processing nuclear@1: nuclear@1: // - returning from this method will end the execution of the thread nuclear@1: // - return value is usually 0 for success nuclear@1: virtual int Run(); nuclear@1: // Called after return/exit function nuclear@1: virtual void OnExit(); nuclear@1: nuclear@1: nuclear@1: // *** Thread management nuclear@1: nuclear@1: // Starts the thread if its not already running nuclear@1: // - internally sets up the threading and calls Run() nuclear@1: // - initial state can either be Running or Suspended, NotRunning will just fail and do nothing nuclear@1: // - returns the exit code nuclear@1: virtual bool Start(ThreadState initialState = Running); nuclear@1: nuclear@1: // Quits with an exit code nuclear@1: virtual void Exit(int exitCode=0); nuclear@1: nuclear@1: // Suspend the thread until resumed nuclear@1: // Returns 1 for success, 0 for failure. nuclear@1: bool Suspend(); nuclear@1: // Resumes currently suspended thread nuclear@1: // Returns 1 for success, 0 for failure. nuclear@1: bool Resume(); nuclear@1: nuclear@1: // Static function to return a pointer to the current thread nuclear@1: //static Thread* GetThread(); nuclear@1: nuclear@1: nuclear@1: // *** Thread status query functions nuclear@1: nuclear@1: bool GetExitFlag() const; nuclear@1: void SetExitFlag(bool exitFlag); nuclear@1: nuclear@1: // Determines whether the thread was running and is now finished nuclear@1: bool IsFinished() const; nuclear@1: // Determines if the thread is currently suspended nuclear@1: bool IsSuspended() const; nuclear@1: // Returns current thread state nuclear@1: ThreadState GetThreadState() const; nuclear@1: nuclear@1: // Returns the number of available CPUs on the system nuclear@1: static int GetCPUCount(); nuclear@1: nuclear@1: // Returns the thread exit code. Exit code is initialized to 0, nuclear@1: // and set to the return value if Run function after the thread is finished. nuclear@1: inline int GetExitCode() const { return ExitCode; } nuclear@1: // Returns an OS handle nuclear@1: #if defined(OVR_OS_WIN32) nuclear@1: void* GetOSHandle() const { return ThreadHandle; } nuclear@1: #else nuclear@1: pthread_t GetOSHandle() const { return ThreadHandle; } nuclear@1: #endif nuclear@1: nuclear@1: #if defined(OVR_OS_WIN32) nuclear@1: ThreadId GetThreadId() const { return IdValue; } nuclear@1: #else nuclear@1: ThreadId GetThreadId() const { return (ThreadId)GetOSHandle(); } nuclear@1: #endif nuclear@1: nuclear@1: static int GetOSPriority(ThreadPriority); nuclear@1: // *** Sleep nuclear@1: nuclear@1: // Sleep secs seconds nuclear@1: static bool Sleep(unsigned secs); nuclear@1: // Sleep msecs milliseconds nuclear@1: static bool MSleep(unsigned msecs); nuclear@1: nuclear@1: nuclear@1: // *** Debugging functionality nuclear@1: #if defined(OVR_OS_WIN32) nuclear@1: virtual void SetThreadName( const char* name ); nuclear@1: #else nuclear@1: virtual void SetThreadName( const char* name ) { OVR_UNUSED(name); } nuclear@1: #endif nuclear@1: nuclear@1: private: nuclear@1: #if defined(OVR_OS_WIN32) nuclear@1: friend unsigned WINAPI Thread_Win32StartFn(void *pthread); nuclear@1: nuclear@1: #else nuclear@1: friend void *Thread_PthreadStartFn(void * phandle); nuclear@1: nuclear@1: static int InitAttr; nuclear@1: static pthread_attr_t Attr; nuclear@1: #endif nuclear@1: nuclear@1: protected: nuclear@1: // Thread state flags nuclear@1: AtomicInt ThreadFlags; nuclear@1: AtomicInt SuspendCount; nuclear@1: UPInt StackSize; nuclear@1: nuclear@1: // Hardware processor which this thread is running on. nuclear@1: int Processor; nuclear@1: ThreadPriority Priority; nuclear@1: nuclear@1: #if defined(OVR_OS_WIN32) nuclear@1: void* ThreadHandle; nuclear@1: volatile ThreadId IdValue; nuclear@1: nuclear@1: // System-specific cleanup function called from destructor nuclear@1: void CleanupSystemThread(); nuclear@1: nuclear@1: #else nuclear@1: pthread_t ThreadHandle; nuclear@1: #endif nuclear@1: nuclear@1: // Exit code of the thread, as returned by Run. nuclear@1: int ExitCode; nuclear@1: nuclear@1: // Internal run function. nuclear@1: int PRun(); nuclear@1: // Finishes the thread and releases internal reference to it. nuclear@1: void FinishAndRelease(); nuclear@1: nuclear@1: void Init(const CreateParams& params); nuclear@1: nuclear@1: // Protected copy constructor nuclear@1: Thread(const Thread &source) { OVR_UNUSED(source); } nuclear@1: nuclear@1: }; nuclear@1: nuclear@1: // Returns the unique Id of a thread it is called on, intended for nuclear@1: // comparison purposes. nuclear@1: ThreadId GetCurrentThreadId(); nuclear@1: nuclear@1: nuclear@1: } // OVR nuclear@1: nuclear@1: #endif // OVR_ENABLE_THREADS nuclear@1: #endif // OVR_Threads_h