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