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.

323 lines
7.8KB

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