Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Thread.hpp 6.8KB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * DISTRHO Plugin Framework (DPF)
  3. * Copyright (C) 2012-2016 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. * or without fee is hereby granted, provided that the above copyright notice and this
  7. * permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  10. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  11. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  12. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  13. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #ifndef DISTRHO_THREAD_HPP_INCLUDED
  17. #define DISTRHO_THREAD_HPP_INCLUDED
  18. #include "Mutex.hpp"
  19. #include "Sleep.hpp"
  20. #include "String.hpp"
  21. #ifdef DISTRHO_OS_LINUX
  22. # include <sys/prctl.h>
  23. #endif
  24. START_NAMESPACE_DISTRHO
  25. // -----------------------------------------------------------------------
  26. // Thread class
  27. class Thread
  28. {
  29. protected:
  30. /*
  31. * Constructor.
  32. */
  33. Thread(const char* const threadName = nullptr) noexcept
  34. : fLock(),
  35. fSignal(),
  36. fName(threadName),
  37. #ifdef PTW32_DLLPORT
  38. fHandle({nullptr, 0}),
  39. #else
  40. fHandle(0),
  41. #endif
  42. fShouldExit(false) {}
  43. /*
  44. * Destructor.
  45. */
  46. virtual ~Thread() /*noexcept*/
  47. {
  48. DISTRHO_SAFE_ASSERT(! isThreadRunning());
  49. stopThread(-1);
  50. }
  51. /*
  52. * Virtual function to be implemented by the subclass.
  53. */
  54. virtual void run() = 0;
  55. // -------------------------------------------------------------------
  56. public:
  57. /*
  58. * Check if the thread is running.
  59. */
  60. bool isThreadRunning() const noexcept
  61. {
  62. #ifdef PTW32_DLLPORT
  63. return (fHandle.p != nullptr);
  64. #else
  65. return (fHandle != 0);
  66. #endif
  67. }
  68. /*
  69. * Check if the thread should exit.
  70. */
  71. bool shouldThreadExit() const noexcept
  72. {
  73. return fShouldExit;
  74. }
  75. /*
  76. * Start the thread.
  77. */
  78. bool startThread() noexcept
  79. {
  80. // check if already running
  81. DISTRHO_SAFE_ASSERT_RETURN(! isThreadRunning(), true);
  82. const MutexLocker ml(fLock);
  83. fShouldExit = false;
  84. pthread_t handle;
  85. if (pthread_create(&handle, nullptr, _entryPoint, this) == 0)
  86. {
  87. #ifdef PTW32_DLLPORT
  88. DISTRHO_SAFE_ASSERT_RETURN(handle.p != nullptr, false);
  89. #else
  90. DISTRHO_SAFE_ASSERT_RETURN(handle != 0, false);
  91. #endif
  92. pthread_detach(handle);
  93. _copyFrom(handle);
  94. // wait for thread to start
  95. fSignal.wait();
  96. return true;
  97. }
  98. return false;
  99. }
  100. /*
  101. * Stop the thread.
  102. * In the 'timeOutMilliseconds':
  103. * = 0 -> no wait
  104. * > 0 -> wait timeout value
  105. * < 0 -> wait forever
  106. */
  107. bool stopThread(const int timeOutMilliseconds) noexcept
  108. {
  109. const MutexLocker ml(fLock);
  110. if (isThreadRunning())
  111. {
  112. signalThreadShouldExit();
  113. if (timeOutMilliseconds != 0)
  114. {
  115. // Wait for the thread to stop
  116. int timeOutCheck = (timeOutMilliseconds == 1 || timeOutMilliseconds == -1) ? timeOutMilliseconds : timeOutMilliseconds/2;
  117. for (; isThreadRunning();)
  118. {
  119. d_msleep(2);
  120. if (timeOutCheck < 0)
  121. continue;
  122. if (timeOutCheck > 0)
  123. timeOutCheck -= 1;
  124. else
  125. break;
  126. }
  127. }
  128. if (isThreadRunning())
  129. {
  130. // should never happen!
  131. d_stderr2("assertion failure: \"! isThreadRunning()\" in file %s, line %i", __FILE__, __LINE__);
  132. // copy thread id so we can clear our one
  133. pthread_t threadId;
  134. _copyTo(threadId);
  135. _init();
  136. try {
  137. pthread_cancel(threadId);
  138. } DISTRHO_SAFE_EXCEPTION("pthread_cancel");
  139. return false;
  140. }
  141. }
  142. return true;
  143. }
  144. /*
  145. * Tell the thread to stop as soon as possible.
  146. */
  147. void signalThreadShouldExit() noexcept
  148. {
  149. fShouldExit = true;
  150. }
  151. // -------------------------------------------------------------------
  152. /*
  153. * Returns the name of the thread.
  154. * This is the name that gets set in the constructor.
  155. */
  156. const String& getThreadName() const noexcept
  157. {
  158. return fName;
  159. }
  160. /*
  161. * Changes the name of the caller thread.
  162. */
  163. static void setCurrentThreadName(const char* const name) noexcept
  164. {
  165. DISTRHO_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  166. #ifdef DISTRHO_OS_LINUX
  167. prctl(PR_SET_NAME, name, 0, 0, 0);
  168. #endif
  169. #if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012
  170. pthread_setname_np(pthread_self(), name);
  171. #endif
  172. }
  173. // -------------------------------------------------------------------
  174. private:
  175. Mutex fLock; // Thread lock
  176. Signal fSignal; // Thread start wait signal
  177. const String fName; // Thread name
  178. volatile pthread_t fHandle; // Handle for this thread
  179. volatile bool fShouldExit; // true if thread should exit
  180. /*
  181. * Init pthread type.
  182. */
  183. void _init() noexcept
  184. {
  185. #ifdef PTW32_DLLPORT
  186. fHandle.p = nullptr;
  187. fHandle.x = 0;
  188. #else
  189. fHandle = 0;
  190. #endif
  191. }
  192. /*
  193. * Copy our pthread type from another var.
  194. */
  195. void _copyFrom(const pthread_t& handle) noexcept
  196. {
  197. #ifdef PTW32_DLLPORT
  198. fHandle.p = handle.p;
  199. fHandle.x = handle.x;
  200. #else
  201. fHandle = handle;
  202. #endif
  203. }
  204. /*
  205. * Copy our pthread type to another var.
  206. */
  207. void _copyTo(volatile pthread_t& handle) const noexcept
  208. {
  209. #ifdef PTW32_DLLPORT
  210. handle.p = fHandle.p;
  211. handle.x = fHandle.x;
  212. #else
  213. handle = fHandle;
  214. #endif
  215. }
  216. /*
  217. * Thread entry point.
  218. */
  219. void _runEntryPoint() noexcept
  220. {
  221. setCurrentThreadName(fName);
  222. // report ready
  223. fSignal.signal();
  224. try {
  225. run();
  226. } catch(...) {}
  227. // done
  228. _init();
  229. }
  230. /*
  231. * Thread entry point.
  232. */
  233. static void* _entryPoint(void* userData) noexcept
  234. {
  235. static_cast<Thread*>(userData)->_runEntryPoint();
  236. return nullptr;
  237. }
  238. DISTRHO_DECLARE_NON_COPY_CLASS(Thread)
  239. };
  240. // -----------------------------------------------------------------------
  241. END_NAMESPACE_DISTRHO
  242. #endif // DISTRHO_THREAD_HPP_INCLUDED