Thread.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #ifdef URHO3D_IS_BUILDING
  5. #include "Urho3D.h"
  6. #else
  7. #include <Urho3D/Urho3D.h>
  8. #endif
  9. #ifndef _WIN32
  10. #include <pthread.h>
  11. using ThreadID = pthread_t;
  12. #else
  13. using ThreadID = unsigned;
  14. #endif
  15. namespace Urho3D
  16. {
  17. /// Operating system thread.
  18. class URHO3D_API Thread
  19. {
  20. public:
  21. /// Construct. Does not start the thread yet.
  22. Thread();
  23. /// Destruct. If running, stop and wait for thread to finish.
  24. virtual ~Thread();
  25. /// The function to run in the thread.
  26. virtual void ThreadFunction() = 0;
  27. /// Start running the thread. Return true if successful, or false if already running or if can not create the thread.
  28. bool Run();
  29. /// Set the running flag to false and wait for the thread to finish.
  30. void Stop();
  31. /// Set thread priority. The thread must have been started first.
  32. void SetPriority(int priority);
  33. /// Return whether thread exists.
  34. bool IsStarted() const { return handle_ != nullptr; }
  35. /// Set the current thread as the main thread.
  36. static void SetMainThread();
  37. /// Return the current thread's ID.
  38. /// @nobind
  39. static ThreadID GetCurrentThreadID();
  40. /// Return whether is executing in the main thread.
  41. static bool IsMainThread();
  42. protected:
  43. /// Thread handle.
  44. void* handle_;
  45. /// Running flag.
  46. volatile bool shouldRun_;
  47. /// Main thread's thread ID.
  48. static ThreadID mainThreadID;
  49. };
  50. }