The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

387 lines
9.9KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. class ThreadPool::ThreadPoolThread : public Thread
  18. {
  19. public:
  20. ThreadPoolThread (ThreadPool& p, size_t stackSize = 0)
  21. : Thread ("Pool", stackSize), currentJob (nullptr), pool (p)
  22. {
  23. }
  24. void run() override
  25. {
  26. while (! threadShouldExit())
  27. if (! pool.runNextJob (*this))
  28. wait (500);
  29. }
  30. ThreadPoolJob* volatile currentJob;
  31. ThreadPool& pool;
  32. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread)
  33. };
  34. //==============================================================================
  35. ThreadPoolJob::ThreadPoolJob (const String& name)
  36. : jobName (name), pool (nullptr),
  37. shouldStop (false), isActive (false), shouldBeDeleted (false)
  38. {
  39. }
  40. ThreadPoolJob::~ThreadPoolJob()
  41. {
  42. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  43. // to remove it first!
  44. jassert (pool == nullptr || ! pool->contains (this));
  45. }
  46. String ThreadPoolJob::getJobName() const
  47. {
  48. return jobName;
  49. }
  50. void ThreadPoolJob::setJobName (const String& newName)
  51. {
  52. jobName = newName;
  53. }
  54. void ThreadPoolJob::signalJobShouldExit()
  55. {
  56. shouldStop = true;
  57. }
  58. ThreadPoolJob* ThreadPoolJob::getCurrentThreadPoolJob()
  59. {
  60. if (ThreadPool::ThreadPoolThread* t = dynamic_cast<ThreadPool::ThreadPoolThread*> (Thread::getCurrentThread()))
  61. return t->currentJob;
  62. return nullptr;
  63. }
  64. //==============================================================================
  65. ThreadPool::ThreadPool (const int numThreads, size_t threadStackSize)
  66. {
  67. jassert (numThreads > 0); // not much point having a pool without any threads!
  68. createThreads (numThreads, threadStackSize);
  69. }
  70. ThreadPool::ThreadPool()
  71. {
  72. createThreads (SystemStats::getNumCpus());
  73. }
  74. ThreadPool::~ThreadPool()
  75. {
  76. removeAllJobs (true, 5000);
  77. stopThreads();
  78. }
  79. void ThreadPool::createThreads (int numThreads, size_t threadStackSize)
  80. {
  81. for (int i = jmax (1, numThreads); --i >= 0;)
  82. threads.add (new ThreadPoolThread (*this, threadStackSize));
  83. for (int i = threads.size(); --i >= 0;)
  84. threads.getUnchecked(i)->startThread();
  85. }
  86. void ThreadPool::stopThreads()
  87. {
  88. for (int i = threads.size(); --i >= 0;)
  89. threads.getUnchecked(i)->signalThreadShouldExit();
  90. for (int i = threads.size(); --i >= 0;)
  91. threads.getUnchecked(i)->stopThread (500);
  92. }
  93. void ThreadPool::addJob (ThreadPoolJob* const job, const bool deleteJobWhenFinished)
  94. {
  95. jassert (job != nullptr);
  96. jassert (job->pool == nullptr);
  97. if (job->pool == nullptr)
  98. {
  99. job->pool = this;
  100. job->shouldStop = false;
  101. job->isActive = false;
  102. job->shouldBeDeleted = deleteJobWhenFinished;
  103. {
  104. const ScopedLock sl (lock);
  105. jobs.add (job);
  106. }
  107. for (int i = threads.size(); --i >= 0;)
  108. threads.getUnchecked(i)->notify();
  109. }
  110. }
  111. int ThreadPool::getNumJobs() const
  112. {
  113. return jobs.size();
  114. }
  115. int ThreadPool::getNumThreads() const
  116. {
  117. return threads.size();
  118. }
  119. ThreadPoolJob* ThreadPool::getJob (const int index) const
  120. {
  121. const ScopedLock sl (lock);
  122. return jobs [index];
  123. }
  124. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  125. {
  126. const ScopedLock sl (lock);
  127. return jobs.contains (const_cast<ThreadPoolJob*> (job));
  128. }
  129. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  130. {
  131. const ScopedLock sl (lock);
  132. return jobs.contains (const_cast<ThreadPoolJob*> (job)) && job->isActive;
  133. }
  134. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job, const int timeOutMs) const
  135. {
  136. if (job != nullptr)
  137. {
  138. const uint32 start = Time::getMillisecondCounter();
  139. while (contains (job))
  140. {
  141. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  142. return false;
  143. jobFinishedSignal.wait (2);
  144. }
  145. }
  146. return true;
  147. }
  148. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  149. const bool interruptIfRunning,
  150. const int timeOutMs)
  151. {
  152. bool dontWait = true;
  153. OwnedArray<ThreadPoolJob> deletionList;
  154. if (job != nullptr)
  155. {
  156. const ScopedLock sl (lock);
  157. if (jobs.contains (job))
  158. {
  159. if (job->isActive)
  160. {
  161. if (interruptIfRunning)
  162. job->signalJobShouldExit();
  163. dontWait = false;
  164. }
  165. else
  166. {
  167. jobs.removeFirstMatchingValue (job);
  168. addToDeleteList (deletionList, job);
  169. }
  170. }
  171. }
  172. return dontWait || waitForJobToFinish (job, timeOutMs);
  173. }
  174. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs, const int timeOutMs,
  175. ThreadPool::JobSelector* const selectedJobsToRemove)
  176. {
  177. Array <ThreadPoolJob*> jobsToWaitFor;
  178. {
  179. OwnedArray<ThreadPoolJob> deletionList;
  180. {
  181. const ScopedLock sl (lock);
  182. for (int i = jobs.size(); --i >= 0;)
  183. {
  184. ThreadPoolJob* const job = jobs.getUnchecked(i);
  185. if (selectedJobsToRemove == nullptr || selectedJobsToRemove->isJobSuitable (job))
  186. {
  187. if (job->isActive)
  188. {
  189. jobsToWaitFor.add (job);
  190. if (interruptRunningJobs)
  191. job->signalJobShouldExit();
  192. }
  193. else
  194. {
  195. jobs.remove (i);
  196. addToDeleteList (deletionList, job);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. const uint32 start = Time::getMillisecondCounter();
  203. for (;;)
  204. {
  205. for (int i = jobsToWaitFor.size(); --i >= 0;)
  206. {
  207. ThreadPoolJob* const job = jobsToWaitFor.getUnchecked (i);
  208. if (! isJobRunning (job))
  209. jobsToWaitFor.remove (i);
  210. }
  211. if (jobsToWaitFor.size() == 0)
  212. break;
  213. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  214. return false;
  215. jobFinishedSignal.wait (20);
  216. }
  217. return true;
  218. }
  219. StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  220. {
  221. StringArray s;
  222. const ScopedLock sl (lock);
  223. for (int i = 0; i < jobs.size(); ++i)
  224. {
  225. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  226. if (job->isActive || ! onlyReturnActiveJobs)
  227. s.add (job->getJobName());
  228. }
  229. return s;
  230. }
  231. bool ThreadPool::setThreadPriorities (const int newPriority)
  232. {
  233. bool ok = true;
  234. for (int i = threads.size(); --i >= 0;)
  235. if (! threads.getUnchecked(i)->setPriority (newPriority))
  236. ok = false;
  237. return ok;
  238. }
  239. ThreadPoolJob* ThreadPool::pickNextJobToRun()
  240. {
  241. OwnedArray<ThreadPoolJob> deletionList;
  242. {
  243. const ScopedLock sl (lock);
  244. for (int i = 0; i < jobs.size(); ++i)
  245. {
  246. ThreadPoolJob* job = jobs[i];
  247. if (job != nullptr && ! job->isActive)
  248. {
  249. if (job->shouldStop)
  250. {
  251. jobs.remove (i);
  252. addToDeleteList (deletionList, job);
  253. --i;
  254. continue;
  255. }
  256. job->isActive = true;
  257. return job;
  258. }
  259. }
  260. }
  261. return nullptr;
  262. }
  263. bool ThreadPool::runNextJob (ThreadPoolThread& thread)
  264. {
  265. if (ThreadPoolJob* const job = pickNextJobToRun())
  266. {
  267. ThreadPoolJob::JobStatus result = ThreadPoolJob::jobHasFinished;
  268. thread.currentJob = job;
  269. try
  270. {
  271. result = job->runJob();
  272. }
  273. catch (...)
  274. {
  275. jassertfalse; // Your runJob() method mustn't throw any exceptions!
  276. }
  277. thread.currentJob = nullptr;
  278. OwnedArray<ThreadPoolJob> deletionList;
  279. {
  280. const ScopedLock sl (lock);
  281. if (jobs.contains (job))
  282. {
  283. job->isActive = false;
  284. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  285. {
  286. jobs.removeFirstMatchingValue (job);
  287. addToDeleteList (deletionList, job);
  288. jobFinishedSignal.signal();
  289. }
  290. else
  291. {
  292. // move the job to the end of the queue if it wants another go
  293. jobs.move (jobs.indexOf (job), -1);
  294. }
  295. }
  296. }
  297. return true;
  298. }
  299. return false;
  300. }
  301. void ThreadPool::addToDeleteList (OwnedArray<ThreadPoolJob>& deletionList, ThreadPoolJob* const job) const
  302. {
  303. job->shouldStop = true;
  304. job->pool = nullptr;
  305. if (job->shouldBeDeleted)
  306. deletionList.add (job);
  307. }