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-2021 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) 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. pthread_attr_setdetachstate(&attr, 1);
  110. const CarlaMutexLocker cml(fLock);
  111. fShouldExit = false;
  112. bool ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  113. pthread_attr_destroy(&attr);
  114. if (withRealtimePriority && !ok)
  115. {
  116. carla_stdout("CarlaThread with realtime priority failed on creation, going with normal priority instead");
  117. pthread_attr_init(&attr);
  118. pthread_attr_setdetachstate(&attr, 1);
  119. ok = pthread_create(&handle, &attr, _entryPoint, this) == 0;
  120. pthread_attr_destroy(&attr);
  121. }
  122. CARLA_SAFE_ASSERT_RETURN(ok, false);
  123. #ifdef PTW32_DLLPORT
  124. CARLA_SAFE_ASSERT_RETURN(handle.p != nullptr, false);
  125. #else
  126. CARLA_SAFE_ASSERT_RETURN(handle != 0, false);
  127. #endif
  128. _copyFrom(handle);
  129. // wait for thread to start
  130. fSignal.wait();
  131. return true;
  132. }
  133. /*
  134. * Stop the thread.
  135. * In the 'timeOutMilliseconds':
  136. * = 0 -> no wait
  137. * > 0 -> wait timeout value
  138. * < 0 -> wait forever
  139. */
  140. bool stopThread(const int timeOutMilliseconds) noexcept
  141. {
  142. const CarlaMutexLocker cml(fLock);
  143. if (isThreadRunning())
  144. {
  145. signalThreadShouldExit();
  146. if (timeOutMilliseconds != 0)
  147. {
  148. // Wait for the thread to stop
  149. int timeOutCheck = (timeOutMilliseconds == 1 || timeOutMilliseconds == -1) ? timeOutMilliseconds : timeOutMilliseconds/2;
  150. for (; isThreadRunning();)
  151. {
  152. carla_msleep(2);
  153. if (timeOutCheck < 0)
  154. continue;
  155. if (timeOutCheck > 0)
  156. timeOutCheck -= 1;
  157. else
  158. break;
  159. }
  160. }
  161. if (isThreadRunning())
  162. {
  163. // should never happen!
  164. carla_stderr2("Carla assertion failure: \"! isThreadRunning()\" in file %s, line %i", __FILE__, __LINE__);
  165. // copy thread id so we can clear our one
  166. pthread_t threadId;
  167. _copyTo(threadId);
  168. _init();
  169. pthread_detach(threadId);
  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. carla_setProcessName(name);
  205. #if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 && !defined(CARLA_OS_GNU_HURD)
  206. pthread_setname_np(pthread_self(), name);
  207. #endif
  208. }
  209. // -------------------------------------------------------------------
  210. private:
  211. CarlaMutex fLock; // Thread lock
  212. CarlaSignal fSignal; // Thread start wait signal
  213. const CarlaString fName; // Thread name
  214. volatile pthread_t fHandle; // Handle for this thread
  215. volatile bool fShouldExit; // true if thread should exit
  216. /*
  217. * Init pthread type.
  218. */
  219. void _init() noexcept
  220. {
  221. #ifdef PTW32_DLLPORT
  222. fHandle.p = nullptr;
  223. fHandle.x = 0;
  224. #else
  225. fHandle = 0;
  226. #endif
  227. }
  228. /*
  229. * Copy our pthread type from another var.
  230. */
  231. void _copyFrom(const pthread_t& handle) noexcept
  232. {
  233. #ifdef PTW32_DLLPORT
  234. fHandle.p = handle.p;
  235. fHandle.x = handle.x;
  236. #else
  237. fHandle = handle;
  238. #endif
  239. }
  240. /*
  241. * Copy our pthread type to another var.
  242. */
  243. void _copyTo(volatile pthread_t& handle) const noexcept
  244. {
  245. #ifdef PTW32_DLLPORT
  246. handle.p = fHandle.p;
  247. handle.x = fHandle.x;
  248. #else
  249. handle = fHandle;
  250. #endif
  251. }
  252. /*
  253. * Thread entry point.
  254. */
  255. void _runEntryPoint() noexcept
  256. {
  257. if (fName.isNotEmpty())
  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