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.

330 lines
8.1KB

  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) 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. pthread_detach(threadId);
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. /*
  175. * Tell the thread to stop as soon as possible.
  176. */
  177. void signalThreadShouldExit() noexcept
  178. {
  179. fShouldExit = true;
  180. }
  181. // -------------------------------------------------------------------
  182. /*
  183. * Returns the name of the thread.
  184. * This is the name that gets set in the constructor.
  185. */
  186. const CarlaString& getThreadName() const noexcept
  187. {
  188. return fName;
  189. }
  190. /*
  191. * Returns the Id/handle of the thread.
  192. */
  193. pthread_t getThreadId() const noexcept
  194. {
  195. return fHandle;
  196. }
  197. /*
  198. * Changes the name of the caller thread.
  199. */
  200. static void setCurrentThreadName(const char* const name) noexcept
  201. {
  202. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  203. carla_setProcessName(name);
  204. #if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 && !defined(CARLA_OS_GNU_HURD)
  205. pthread_setname_np(pthread_self(), name);
  206. #endif
  207. }
  208. // -------------------------------------------------------------------
  209. private:
  210. CarlaMutex fLock; // Thread lock
  211. CarlaSignal fSignal; // Thread start wait signal
  212. const CarlaString fName; // Thread name
  213. volatile pthread_t fHandle; // Handle for this thread
  214. volatile bool fShouldExit; // true if thread should exit
  215. /*
  216. * Init pthread type.
  217. */
  218. void _init() noexcept
  219. {
  220. #ifdef PTW32_DLLPORT
  221. fHandle.p = nullptr;
  222. fHandle.x = 0;
  223. #else
  224. fHandle = 0;
  225. #endif
  226. }
  227. /*
  228. * Copy our pthread type from another var.
  229. */
  230. void _copyFrom(const pthread_t& handle) noexcept
  231. {
  232. #ifdef PTW32_DLLPORT
  233. fHandle.p = handle.p;
  234. fHandle.x = handle.x;
  235. #else
  236. fHandle = handle;
  237. #endif
  238. }
  239. /*
  240. * Copy our pthread type to another var.
  241. */
  242. void _copyTo(volatile pthread_t& handle) const noexcept
  243. {
  244. #ifdef PTW32_DLLPORT
  245. handle.p = fHandle.p;
  246. handle.x = fHandle.x;
  247. #else
  248. handle = fHandle;
  249. #endif
  250. }
  251. /*
  252. * Thread entry point.
  253. */
  254. void _runEntryPoint() noexcept
  255. {
  256. if (fName.isNotEmpty())
  257. setCurrentThreadName(fName);
  258. // report ready
  259. fSignal.signal();
  260. try {
  261. run();
  262. } catch(...) {}
  263. // done
  264. _init();
  265. }
  266. /*
  267. * Thread entry point.
  268. */
  269. static void* _entryPoint(void* userData) noexcept
  270. {
  271. static_cast<CarlaThread*>(userData)->_runEntryPoint();
  272. return nullptr;
  273. }
  274. CARLA_DECLARE_NON_COPY_CLASS(CarlaThread)
  275. };
  276. // -----------------------------------------------------------------------
  277. #endif // CARLA_THREAD_HPP_INCLUDED