2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
11 // Thread.h: interface for the CThread class.
13 //////////////////////////////////////////////////////////////////////
20 #include <mach/mach.h>
26 enum class ThreadPriority
35 * \brief Do not use this for priority. It is only needed to count the
36 * amount of values in the ThreadPriority enum.
47 explicit CThread(const char* ThreadName
);
50 CThread(IRunnable
* pRunnable
, const char* ThreadName
);
52 void Create(bool bAutoDelete
= false);
54 template<typename Rep
, typename Period
>
55 void Sleep(std::chrono::duration
<Rep
, Period
> duration
)
57 if (duration
> std::chrono::milliseconds(10) && IsCurrentThread())
58 m_StopEvent
.Wait(duration
);
60 std::this_thread::sleep_for(duration
);
63 bool IsAutoDelete() const;
64 virtual void StopThread(bool bWait
= true);
65 bool IsRunning() const;
67 bool IsCurrentThread() const;
68 bool Join(std::chrono::milliseconds duration
);
70 inline static const std::thread::id
GetCurrentThreadId()
72 return std::this_thread::get_id();
76 * \brief Set the threads priority. This uses the platforms
77 * native threading library to do so.
80 bool SetPriority(const ThreadPriority
& priority
);
82 static CThread
* GetCurrentThread();
84 virtual void OnException(){} // signal termination handler
87 virtual void OnStartup() {}
88 virtual void OnExit() {}
89 virtual void Process();
91 std::atomic
<bool> m_bStop
;
93 enum WaitResponse
{ WAIT_INTERRUPTED
= -1, WAIT_SIGNALED
= 0, WAIT_TIMEDOUT
= 1 };
96 * This call will wait on a CEvent in an interruptible way such that if
97 * stop is called on the thread the wait will return with a response
98 * indicating what happened.
100 inline WaitResponse
AbortableWait(CEvent
& event
,
101 std::chrono::milliseconds duration
=
102 std::chrono::milliseconds(-1) /* indicates wait forever*/)
104 XbmcThreads::CEventGroup group
{&event
, &m_StopEvent
};
105 const CEvent
* result
=
106 duration
< std::chrono::milliseconds::zero() ? group
.wait() : group
.wait(duration
);
107 return result
== &event
? WAIT_SIGNALED
:
108 (result
== NULL
? WAIT_TIMEDOUT
: WAIT_INTERRUPTED
);
114 bool m_bAutoDelete
= false;
117 CCriticalSection m_CriticalSection
;
118 IRunnable
* m_pRunnable
;
120 std::string m_ThreadName
;
121 std::thread
* m_thread
= nullptr;
122 std::future
<bool> m_future
;
124 std::unique_ptr
<IThreadImpl
> m_impl
;