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.

381 lines
9.8KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. ThreadPoolJob::ThreadPoolJob (const String& name)
  22. : jobName (name),
  23. pool (nullptr),
  24. shouldStop (false),
  25. isActive (false),
  26. shouldBeDeleted (false)
  27. {
  28. }
  29. ThreadPoolJob::~ThreadPoolJob()
  30. {
  31. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  32. // to remove it first!
  33. jassert (pool == nullptr || ! pool->contains (this));
  34. }
  35. String ThreadPoolJob::getJobName() const
  36. {
  37. return jobName;
  38. }
  39. void ThreadPoolJob::setJobName (const String& newName)
  40. {
  41. jobName = newName;
  42. }
  43. void ThreadPoolJob::signalJobShouldExit()
  44. {
  45. shouldStop = true;
  46. }
  47. //==============================================================================
  48. class ThreadPool::ThreadPoolThread : public Thread
  49. {
  50. public:
  51. ThreadPoolThread (ThreadPool& pool_)
  52. : Thread ("Pool"),
  53. pool (pool_)
  54. {
  55. }
  56. void run() override
  57. {
  58. while (! threadShouldExit())
  59. {
  60. if (! pool.runNextJob())
  61. wait (500);
  62. }
  63. }
  64. private:
  65. ThreadPool& pool;
  66. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread)
  67. };
  68. //==============================================================================
  69. ThreadPool::ThreadPool (const int numThreads)
  70. {
  71. jassert (numThreads > 0); // not much point having a pool without any threads!
  72. createThreads (numThreads);
  73. }
  74. ThreadPool::ThreadPool()
  75. {
  76. createThreads (SystemStats::getNumCpus());
  77. }
  78. ThreadPool::~ThreadPool()
  79. {
  80. removeAllJobs (true, 5000);
  81. stopThreads();
  82. }
  83. void ThreadPool::createThreads (int numThreads)
  84. {
  85. for (int i = jmax (1, numThreads); --i >= 0;)
  86. threads.add (new ThreadPoolThread (*this));
  87. for (int i = threads.size(); --i >= 0;)
  88. threads.getUnchecked(i)->startThread();
  89. }
  90. void ThreadPool::stopThreads()
  91. {
  92. for (int i = threads.size(); --i >= 0;)
  93. threads.getUnchecked(i)->signalThreadShouldExit();
  94. for (int i = threads.size(); --i >= 0;)
  95. threads.getUnchecked(i)->stopThread (500);
  96. }
  97. void ThreadPool::addJob (ThreadPoolJob* const job, const bool deleteJobWhenFinished)
  98. {
  99. jassert (job != nullptr);
  100. jassert (job->pool == nullptr);
  101. if (job->pool == nullptr)
  102. {
  103. job->pool = this;
  104. job->shouldStop = false;
  105. job->isActive = false;
  106. job->shouldBeDeleted = deleteJobWhenFinished;
  107. {
  108. const ScopedLock sl (lock);
  109. jobs.add (job);
  110. }
  111. for (int i = threads.size(); --i >= 0;)
  112. threads.getUnchecked(i)->notify();
  113. }
  114. }
  115. int ThreadPool::getNumJobs() const
  116. {
  117. return jobs.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,
  135. const int timeOutMs) const
  136. {
  137. if (job != nullptr)
  138. {
  139. const uint32 start = Time::getMillisecondCounter();
  140. while (contains (job))
  141. {
  142. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  143. return false;
  144. jobFinishedSignal.wait (2);
  145. }
  146. }
  147. return true;
  148. }
  149. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  150. const bool interruptIfRunning,
  151. const int timeOutMs)
  152. {
  153. bool dontWait = true;
  154. OwnedArray<ThreadPoolJob> deletionList;
  155. if (job != nullptr)
  156. {
  157. const ScopedLock sl (lock);
  158. if (jobs.contains (job))
  159. {
  160. if (job->isActive)
  161. {
  162. if (interruptIfRunning)
  163. job->signalJobShouldExit();
  164. dontWait = false;
  165. }
  166. else
  167. {
  168. jobs.removeFirstMatchingValue (job);
  169. addToDeleteList (deletionList, job);
  170. }
  171. }
  172. }
  173. return dontWait || waitForJobToFinish (job, timeOutMs);
  174. }
  175. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs, const int timeOutMs,
  176. ThreadPool::JobSelector* selectedJobsToRemove)
  177. {
  178. Array <ThreadPoolJob*> jobsToWaitFor;
  179. {
  180. OwnedArray<ThreadPoolJob> deletionList;
  181. {
  182. const ScopedLock sl (lock);
  183. for (int i = jobs.size(); --i >= 0;)
  184. {
  185. ThreadPoolJob* const job = jobs.getUnchecked(i);
  186. if (selectedJobsToRemove == nullptr || selectedJobsToRemove->isJobSuitable (job))
  187. {
  188. if (job->isActive)
  189. {
  190. jobsToWaitFor.add (job);
  191. if (interruptRunningJobs)
  192. job->signalJobShouldExit();
  193. }
  194. else
  195. {
  196. jobs.remove (i);
  197. addToDeleteList (deletionList, job);
  198. }
  199. }
  200. }
  201. }
  202. }
  203. const uint32 start = Time::getMillisecondCounter();
  204. for (;;)
  205. {
  206. for (int i = jobsToWaitFor.size(); --i >= 0;)
  207. {
  208. ThreadPoolJob* const job = jobsToWaitFor.getUnchecked (i);
  209. if (! isJobRunning (job))
  210. jobsToWaitFor.remove (i);
  211. }
  212. if (jobsToWaitFor.size() == 0)
  213. break;
  214. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  215. return false;
  216. jobFinishedSignal.wait (20);
  217. }
  218. return true;
  219. }
  220. StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  221. {
  222. StringArray s;
  223. const ScopedLock sl (lock);
  224. for (int i = 0; i < jobs.size(); ++i)
  225. {
  226. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  227. if (job->isActive || ! onlyReturnActiveJobs)
  228. s.add (job->getJobName());
  229. }
  230. return s;
  231. }
  232. bool ThreadPool::setThreadPriorities (const int newPriority)
  233. {
  234. bool ok = true;
  235. for (int i = threads.size(); --i >= 0;)
  236. if (! threads.getUnchecked(i)->setPriority (newPriority))
  237. ok = false;
  238. return ok;
  239. }
  240. ThreadPoolJob* ThreadPool::pickNextJobToRun()
  241. {
  242. OwnedArray<ThreadPoolJob> deletionList;
  243. {
  244. const ScopedLock sl (lock);
  245. for (int i = 0; i < jobs.size(); ++i)
  246. {
  247. ThreadPoolJob* job = jobs[i];
  248. if (job != nullptr && ! job->isActive)
  249. {
  250. if (job->shouldStop)
  251. {
  252. jobs.remove (i);
  253. addToDeleteList (deletionList, job);
  254. --i;
  255. continue;
  256. }
  257. job->isActive = true;
  258. return job;
  259. }
  260. }
  261. }
  262. return nullptr;
  263. }
  264. bool ThreadPool::runNextJob()
  265. {
  266. ThreadPoolJob* const job = pickNextJobToRun();
  267. if (job == nullptr)
  268. return false;
  269. ThreadPoolJob::JobStatus result = ThreadPoolJob::jobHasFinished;
  270. JUCE_TRY
  271. {
  272. result = job->runJob();
  273. }
  274. JUCE_CATCH_ALL_ASSERT
  275. OwnedArray<ThreadPoolJob> deletionList;
  276. {
  277. const ScopedLock sl (lock);
  278. if (jobs.contains (job))
  279. {
  280. job->isActive = false;
  281. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  282. {
  283. jobs.removeFirstMatchingValue (job);
  284. addToDeleteList (deletionList, job);
  285. jobFinishedSignal.signal();
  286. }
  287. else
  288. {
  289. // move the job to the end of the queue if it wants another go
  290. jobs.move (jobs.indexOf (job), -1);
  291. }
  292. }
  293. }
  294. return true;
  295. }
  296. void ThreadPool::addToDeleteList (OwnedArray<ThreadPoolJob>& deletionList, ThreadPoolJob* const job) const
  297. {
  298. job->shouldStop = true;
  299. job->pool = nullptr;
  300. if (job->shouldBeDeleted)
  301. deletionList.add (job);
  302. }