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.

332 lines
8.2KB

  1. /*
  2. * Carla Thread
  3. * Copyright (C) 2013-2019 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. #include "CarlaProcessUtils.hpp"
  22. #ifdef CARLA_OS_LINUX
  23. # include <sys/prctl.h>
  24. #endif
  25. // -----------------------------------------------------------------------
  26. // CarlaThread class
  27. class CarlaThread
  28. {
  29. protected:
  30. /*
  31. * Constructor.
  32. */
  33. CarlaThread(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 ~CarlaThread() /*noexcept*/
  47. {
  48. CARLA_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(const bool withRealtimePriority = false) noexcept
  79. {
  80. // check if already running
  81. CARLA_SAFE_ASSERT_RETURN(! isThreadRunning(), true);
  82. pthread_t handle;
  83. pthread_attr_t attr;
  84. pthread_attr_init(&attr);
  85. struct sched_param sched_param;
  86. carla_zeroStruct(sched_param);
  87. if (withRealtimePriority)
  88. {
  89. sched_param.sched_priority = 80;
  90. #ifndef CARLA_OS_HAIKU
  91. if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0 &&
  92. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0 &&
  93. # ifndef CARLA_OS_WIN
  94. (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0 ||
  95. pthread_attr_setschedpolicy(&attr, SCHED_RR) == 0) &&
  96. # endif
  97. pthread_attr_setschedparam(&attr, &sched_param) == 0)
  98. {
  99. carla_stdout("CarlaThread setup with realtime priority successful");
  100. }
  101. else
  102. #endif
  103. {
  104. carla_stdout("CarlaThread setup with realtime priority failed, going with normal priority instead");
  105. pthread_attr_destroy(&attr);
  106. pthread_attr_init(&attr);
  107. }
  108. }
  109. const CarlaMutexLocker cml(fLock);
  110. fShouldExit = false;
  111. bool ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  112. pthread_attr_destroy(&attr);
  113. if (withRealtimePriority && !ok)
  114. {
  115. carla_stdout("CarlaThread with realtime priority failed on creation, going with normal priority instead");
  116. pthread_attr_init(&attr);
  117. ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  118. pthread_attr_destroy(&attr);
  119. }
  120. CARLA_SAFE_ASSERT_RETURN(ok, false);
  121. #ifdef PTW32_DLLPORT
  122. CARLA_SAFE_ASSERT_RETURN(handle.p != nullptr, false);
  123. #else
  124. CARLA_SAFE_ASSERT_RETURN(handle != 0, false);
  125. #endif
  126. pthread_detach(handle);
  127. _copyFrom(handle);
  128. // wait for thread to start
  129. fSignal.wait();
  130. return true;
  131. }
  132. /*
  133. * Stop the thread.
  134. * In the 'timeOutMilliseconds':
  135. * = 0 -> no wait
  136. * > 0 -> wait timeout value
  137. * < 0 -> wait forever
  138. */
  139. bool stopThread(const int timeOutMilliseconds) noexcept
  140. {
  141. const CarlaMutexLocker cml(fLock);
  142. if (isThreadRunning())
  143. {
  144. signalThreadShouldExit();
  145. if (timeOutMilliseconds != 0)
  146. {
  147. // Wait for the thread to stop
  148. int timeOutCheck = (timeOutMilliseconds == 1 || timeOutMilliseconds == -1) ? timeOutMilliseconds : timeOutMilliseconds/2;
  149. for (; isThreadRunning();)
  150. {
  151. carla_msleep(2);
  152. if (timeOutCheck < 0)
  153. continue;
  154. if (timeOutCheck > 0)
  155. timeOutCheck -= 1;
  156. else
  157. break;
  158. }
  159. }
  160. if (isThreadRunning())
  161. {
  162. // should never happen!
  163. carla_stderr2("Carla assertion failure: \"! isThreadRunning()\" in file %s, line %i", __FILE__, __LINE__);
  164. // copy thread id so we can clear our one
  165. pthread_t threadId;
  166. _copyTo(threadId);
  167. _init();
  168. try {
  169. pthread_cancel(threadId);
  170. } CARLA_SAFE_EXCEPTION("pthread_cancel");
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. /*
  177. * Tell the thread to stop as soon as possible.
  178. */
  179. void signalThreadShouldExit() noexcept
  180. {
  181. fShouldExit = true;
  182. }
  183. // -------------------------------------------------------------------
  184. /*
  185. * Returns the name of the thread.
  186. * This is the name that gets set in the constructor.
  187. */
  188. const CarlaString& getThreadName() const noexcept
  189. {
  190. return fName;
  191. }
  192. /*
  193. * Returns the Id/handle of the thread.
  194. */
  195. pthread_t getThreadId() const noexcept
  196. {
  197. return fHandle;
  198. }
  199. /*
  200. * Changes the name of the caller thread.
  201. */
  202. static void setCurrentThreadName(const char* const name) noexcept
  203. {
  204. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  205. carla_setProcessName(name);
  206. #if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 && !defined(CARLA_OS_GNU_HURD)
  207. pthread_setname_np(pthread_self(), name);
  208. #endif
  209. }
  210. // -------------------------------------------------------------------
  211. private:
  212. CarlaMutex fLock; // Thread lock
  213. CarlaSignal fSignal; // Thread start wait signal
  214. const CarlaString fName; // Thread name
  215. volatile pthread_t fHandle; // Handle for this thread
  216. volatile bool fShouldExit; // true if thread should exit
  217. /*
  218. * Init pthread type.
  219. */
  220. void _init() noexcept
  221. {
  222. #ifdef PTW32_DLLPORT
  223. fHandle.p = nullptr;
  224. fHandle.x = 0;
  225. #else
  226. fHandle = 0;
  227. #endif
  228. }
  229. /*
  230. * Copy our pthread type from another var.
  231. */
  232. void _copyFrom(const pthread_t& handle) noexcept
  233. {
  234. #ifdef PTW32_DLLPORT
  235. fHandle.p = handle.p;
  236. fHandle.x = handle.x;
  237. #else
  238. fHandle = handle;
  239. #endif
  240. }
  241. /*
  242. * Copy our pthread type to another var.
  243. */
  244. void _copyTo(volatile pthread_t& handle) const noexcept
  245. {
  246. #ifdef PTW32_DLLPORT
  247. handle.p = fHandle.p;
  248. handle.x = fHandle.x;
  249. #else
  250. handle = fHandle;
  251. #endif
  252. }
  253. /*
  254. * Thread entry point.
  255. */
  256. void _runEntryPoint() noexcept
  257. {
  258. setCurrentThreadName(fName);
  259. // report ready
  260. fSignal.signal();
  261. try {
  262. run();
  263. } catch(...) {}
  264. // done
  265. _init();
  266. }
  267. /*
  268. * Thread entry point.
  269. */
  270. static void* _entryPoint(void* userData) noexcept
  271. {
  272. static_cast<CarlaThread*>(userData)->_runEntryPoint();
  273. return nullptr;
  274. }
  275. CARLA_DECLARE_NON_COPY_CLASS(CarlaThread)
  276. };
  277. // -----------------------------------------------------------------------
  278. #endif // CARLA_THREAD_HPP_INCLUDED