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.

CarlaThread.hpp 8.2KB

8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. * Carla Thread
  3. * Copyright (C) 2013-2016 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #ifndef CARLA_THREAD_HPP_INCLUDED
  18. #define CARLA_THREAD_HPP_INCLUDED
  19. #include "CarlaMutex.hpp"
  20. #include "CarlaString.hpp"
  21. #ifdef CARLA_OS_LINUX
  22. # include <sys/prctl.h>
  23. #endif
  24. // -----------------------------------------------------------------------
  25. // CarlaThread class
  26. class CarlaThread
  27. {
  28. protected:
  29. /*
  30. * Constructor.
  31. */
  32. CarlaThread(const char* const threadName = nullptr) noexcept
  33. : fLock(),
  34. fSignal(),
  35. fName(threadName),
  36. #ifdef PTW32_DLLPORT
  37. fHandle({nullptr, 0}),
  38. #else
  39. fHandle(0),
  40. #endif
  41. fShouldExit(false) {}
  42. /*
  43. * Destructor.
  44. */
  45. virtual ~CarlaThread() /*noexcept*/
  46. {
  47. CARLA_SAFE_ASSERT(! isThreadRunning());
  48. stopThread(-1);
  49. }
  50. /*
  51. * Virtual function to be implemented by the subclass.
  52. */
  53. virtual void run() = 0;
  54. // -------------------------------------------------------------------
  55. public:
  56. /*
  57. * Check if the thread is running.
  58. */
  59. bool isThreadRunning() const noexcept
  60. {
  61. #ifdef PTW32_DLLPORT
  62. return (fHandle.p != nullptr);
  63. #else
  64. return (fHandle != 0);
  65. #endif
  66. }
  67. /*
  68. * Check if the thread should exit.
  69. */
  70. bool shouldThreadExit() const noexcept
  71. {
  72. return fShouldExit;
  73. }
  74. /*
  75. * Start the thread.
  76. */
  77. bool startThread(const bool withRealtimePriority = false) noexcept
  78. {
  79. // check if already running
  80. CARLA_SAFE_ASSERT_RETURN(! isThreadRunning(), true);
  81. pthread_t handle;
  82. pthread_attr_t attr;
  83. pthread_attr_init(&attr);
  84. struct sched_param sched_param;
  85. carla_zeroStruct(sched_param);
  86. if (withRealtimePriority)
  87. {
  88. sched_param.sched_priority = 80;
  89. #ifndef CARLA_OS_HAIKU
  90. if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0 &&
  91. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0 &&
  92. # ifndef CARLA_OS_WIN
  93. (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0 ||
  94. pthread_attr_setschedpolicy(&attr, SCHED_RR) == 0) &&
  95. # endif
  96. pthread_attr_setschedparam(&attr, &sched_param) == 0)
  97. {
  98. carla_stdout("CarlaThread setup with realtime priority successful");
  99. }
  100. else
  101. #endif
  102. {
  103. carla_stdout("CarlaThread setup with realtime priority failed, going with normal priority instead");
  104. pthread_attr_destroy(&attr);
  105. pthread_attr_init(&attr);
  106. }
  107. }
  108. const CarlaMutexLocker cml(fLock);
  109. fShouldExit = false;
  110. bool ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  111. pthread_attr_destroy(&attr);
  112. if (withRealtimePriority && !ok)
  113. {
  114. carla_stdout("CarlaThread with realtime priority failed on creation, going with normal priority instead");
  115. pthread_attr_init(&attr);
  116. ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  117. pthread_attr_destroy(&attr);
  118. }
  119. CARLA_SAFE_ASSERT_RETURN(ok, false);
  120. #ifdef PTW32_DLLPORT
  121. CARLA_SAFE_ASSERT_RETURN(handle.p != nullptr, false);
  122. #else
  123. CARLA_SAFE_ASSERT_RETURN(handle != 0, false);
  124. #endif
  125. pthread_detach(handle);
  126. _copyFrom(handle);
  127. // wait for thread to start
  128. fSignal.wait();
  129. return true;
  130. }
  131. /*
  132. * Stop the thread.
  133. * In the 'timeOutMilliseconds':
  134. * = 0 -> no wait
  135. * > 0 -> wait timeout value
  136. * < 0 -> wait forever
  137. */
  138. bool stopThread(const int timeOutMilliseconds) noexcept
  139. {
  140. const CarlaMutexLocker cml(fLock);
  141. if (isThreadRunning())
  142. {
  143. signalThreadShouldExit();
  144. if (timeOutMilliseconds != 0)
  145. {
  146. // Wait for the thread to stop
  147. int timeOutCheck = (timeOutMilliseconds == 1 || timeOutMilliseconds == -1) ? timeOutMilliseconds : timeOutMilliseconds/2;
  148. for (; isThreadRunning();)
  149. {
  150. carla_msleep(2);
  151. if (timeOutCheck < 0)
  152. continue;
  153. if (timeOutCheck > 0)
  154. timeOutCheck -= 1;
  155. else
  156. break;
  157. }
  158. }
  159. if (isThreadRunning())
  160. {
  161. // should never happen!
  162. carla_stderr2("Carla assertion failure: \"! isThreadRunning()\" in file %s, line %i", __FILE__, __LINE__);
  163. // copy thread id so we can clear our one
  164. pthread_t threadId;
  165. _copyTo(threadId);
  166. _init();
  167. try {
  168. pthread_cancel(threadId);
  169. } CARLA_SAFE_EXCEPTION("pthread_cancel");
  170. return false;
  171. }
  172. }
  173. return true;
  174. }
  175. /*
  176. * Tell the thread to stop as soon as possible.
  177. */
  178. void signalThreadShouldExit() noexcept
  179. {
  180. fShouldExit = true;
  181. }
  182. // -------------------------------------------------------------------
  183. /*
  184. * Returns the name of the thread.
  185. * This is the name that gets set in the constructor.
  186. */
  187. const CarlaString& getThreadName() const noexcept
  188. {
  189. return fName;
  190. }
  191. /*
  192. * Returns the Id/handle of the thread.
  193. */
  194. pthread_t getThreadId() const noexcept
  195. {
  196. return fHandle;
  197. }
  198. /*
  199. * Changes the name of the caller thread.
  200. */
  201. static void setCurrentThreadName(const char* const name) noexcept
  202. {
  203. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  204. #ifdef CARLA_OS_LINUX
  205. prctl(PR_SET_NAME, name, 0, 0, 0);
  206. #endif
  207. #if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 && !defined(CARLA_OS_GNU_HURD)
  208. pthread_setname_np(pthread_self(), name);
  209. #endif
  210. }
  211. // -------------------------------------------------------------------
  212. private:
  213. CarlaMutex fLock; // Thread lock
  214. CarlaSignal fSignal; // Thread start wait signal
  215. const CarlaString fName; // Thread name
  216. volatile pthread_t fHandle; // Handle for this thread
  217. volatile bool fShouldExit; // true if thread should exit
  218. /*
  219. * Init pthread type.
  220. */
  221. void _init() noexcept
  222. {
  223. #ifdef PTW32_DLLPORT
  224. fHandle.p = nullptr;
  225. fHandle.x = 0;
  226. #else
  227. fHandle = 0;
  228. #endif
  229. }
  230. /*
  231. * Copy our pthread type from another var.
  232. */
  233. void _copyFrom(const pthread_t& handle) noexcept
  234. {
  235. #ifdef PTW32_DLLPORT
  236. fHandle.p = handle.p;
  237. fHandle.x = handle.x;
  238. #else
  239. fHandle = handle;
  240. #endif
  241. }
  242. /*
  243. * Copy our pthread type to another var.
  244. */
  245. void _copyTo(volatile pthread_t& handle) const noexcept
  246. {
  247. #ifdef PTW32_DLLPORT
  248. handle.p = fHandle.p;
  249. handle.x = fHandle.x;
  250. #else
  251. handle = fHandle;
  252. #endif
  253. }
  254. /*
  255. * Thread entry point.
  256. */
  257. void _runEntryPoint() noexcept
  258. {
  259. setCurrentThreadName(fName);
  260. // report ready
  261. fSignal.signal();
  262. try {
  263. run();
  264. } catch(...) {}
  265. // done
  266. _init();
  267. }
  268. /*
  269. * Thread entry point.
  270. */
  271. static void* _entryPoint(void* userData) noexcept
  272. {
  273. static_cast<CarlaThread*>(userData)->_runEntryPoint();
  274. return nullptr;
  275. }
  276. CARLA_DECLARE_NON_COPY_CLASS(CarlaThread)
  277. };
  278. // -----------------------------------------------------------------------
  279. #endif // CARLA_THREAD_HPP_INCLUDED