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.

409 lines
10KB

  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)
  21. : Thread ("Pool", stackSize), 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 = nullptr;
  31. ThreadPool& pool;
  32. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread)
  33. };
  34. //==============================================================================
  35. ThreadPoolJob::ThreadPoolJob (const String& name) : jobName (name)
  36. {
  37. }
  38. ThreadPoolJob::~ThreadPoolJob()
  39. {
  40. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  41. // to remove it first!
  42. jassert (pool == nullptr || ! pool->contains (this));
  43. }
  44. String ThreadPoolJob::getJobName() const
  45. {
  46. return jobName;
  47. }
  48. void ThreadPoolJob::setJobName (const String& newName)
  49. {
  50. jobName = newName;
  51. }
  52. void ThreadPoolJob::signalJobShouldExit()
  53. {
  54. shouldStop = true;
  55. }
  56. ThreadPoolJob* ThreadPoolJob::getCurrentThreadPoolJob()
  57. {
  58. if (auto* t = dynamic_cast<ThreadPool::ThreadPoolThread*> (Thread::getCurrentThread()))
  59. return t->currentJob;
  60. return nullptr;
  61. }
  62. //==============================================================================
  63. ThreadPool::ThreadPool (const int numThreads, size_t threadStackSize)
  64. {
  65. jassert (numThreads > 0); // not much point having a pool without any threads!
  66. createThreads (numThreads, threadStackSize);
  67. }
  68. ThreadPool::ThreadPool()
  69. {
  70. createThreads (SystemStats::getNumCpus());
  71. }
  72. ThreadPool::~ThreadPool()
  73. {
  74. removeAllJobs (true, 5000);
  75. stopThreads();
  76. }
  77. void ThreadPool::createThreads (int numThreads, size_t threadStackSize)
  78. {
  79. for (int i = jmax (1, numThreads); --i >= 0;)
  80. threads.add (new ThreadPoolThread (*this, threadStackSize));
  81. for (auto* t : threads)
  82. t->startThread();
  83. }
  84. void ThreadPool::stopThreads()
  85. {
  86. for (auto* t : threads)
  87. t->signalThreadShouldExit();
  88. for (auto* t : threads)
  89. t->stopThread (500);
  90. }
  91. void ThreadPool::addJob (ThreadPoolJob* const job, const bool deleteJobWhenFinished)
  92. {
  93. jassert (job != nullptr);
  94. jassert (job->pool == nullptr);
  95. if (job->pool == nullptr)
  96. {
  97. job->pool = this;
  98. job->shouldStop = false;
  99. job->isActive = false;
  100. job->shouldBeDeleted = deleteJobWhenFinished;
  101. {
  102. const ScopedLock sl (lock);
  103. jobs.add (job);
  104. }
  105. for (auto* t : threads)
  106. t->notify();
  107. }
  108. }
  109. void ThreadPool::addJob (std::function<ThreadPoolJob::JobStatus()> jobToRun)
  110. {
  111. struct LambdaJobWrapper : public ThreadPoolJob
  112. {
  113. LambdaJobWrapper (std::function<ThreadPoolJob::JobStatus()> j) : ThreadPoolJob ("lambda"), job (j) {}
  114. JobStatus runJob() override { return job(); }
  115. std::function<ThreadPoolJob::JobStatus()> job;
  116. };
  117. addJob (new LambdaJobWrapper (jobToRun), true);
  118. }
  119. void ThreadPool::addJob (std::function<void()> jobToRun)
  120. {
  121. struct LambdaJobWrapper : public ThreadPoolJob
  122. {
  123. LambdaJobWrapper (std::function<void()> j) : ThreadPoolJob ("lambda"), job (j) {}
  124. JobStatus runJob() override { job(); return ThreadPoolJob::jobHasFinished; }
  125. std::function<void()> job;
  126. };
  127. addJob (new LambdaJobWrapper (jobToRun), true);
  128. }
  129. int ThreadPool::getNumJobs() const
  130. {
  131. return jobs.size();
  132. }
  133. int ThreadPool::getNumThreads() const
  134. {
  135. return threads.size();
  136. }
  137. ThreadPoolJob* ThreadPool::getJob (const int index) const
  138. {
  139. const ScopedLock sl (lock);
  140. return jobs [index];
  141. }
  142. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  143. {
  144. const ScopedLock sl (lock);
  145. return jobs.contains (const_cast<ThreadPoolJob*> (job));
  146. }
  147. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  148. {
  149. const ScopedLock sl (lock);
  150. return jobs.contains (const_cast<ThreadPoolJob*> (job)) && job->isActive;
  151. }
  152. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job, const int timeOutMs) const
  153. {
  154. if (job != nullptr)
  155. {
  156. auto start = Time::getMillisecondCounter();
  157. while (contains (job))
  158. {
  159. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  160. return false;
  161. jobFinishedSignal.wait (2);
  162. }
  163. }
  164. return true;
  165. }
  166. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  167. const bool interruptIfRunning,
  168. const int timeOutMs)
  169. {
  170. bool dontWait = true;
  171. OwnedArray<ThreadPoolJob> deletionList;
  172. if (job != nullptr)
  173. {
  174. const ScopedLock sl (lock);
  175. if (jobs.contains (job))
  176. {
  177. if (job->isActive)
  178. {
  179. if (interruptIfRunning)
  180. job->signalJobShouldExit();
  181. dontWait = false;
  182. }
  183. else
  184. {
  185. jobs.removeFirstMatchingValue (job);
  186. addToDeleteList (deletionList, job);
  187. }
  188. }
  189. }
  190. return dontWait || waitForJobToFinish (job, timeOutMs);
  191. }
  192. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs, const int timeOutMs,
  193. ThreadPool::JobSelector* const selectedJobsToRemove)
  194. {
  195. Array<ThreadPoolJob*> jobsToWaitFor;
  196. {
  197. OwnedArray<ThreadPoolJob> deletionList;
  198. {
  199. const ScopedLock sl (lock);
  200. for (int i = jobs.size(); --i >= 0;)
  201. {
  202. auto* job = jobs.getUnchecked(i);
  203. if (selectedJobsToRemove == nullptr || selectedJobsToRemove->isJobSuitable (job))
  204. {
  205. if (job->isActive)
  206. {
  207. jobsToWaitFor.add (job);
  208. if (interruptRunningJobs)
  209. job->signalJobShouldExit();
  210. }
  211. else
  212. {
  213. jobs.remove (i);
  214. addToDeleteList (deletionList, job);
  215. }
  216. }
  217. }
  218. }
  219. }
  220. const uint32 start = Time::getMillisecondCounter();
  221. for (;;)
  222. {
  223. for (int i = jobsToWaitFor.size(); --i >= 0;)
  224. {
  225. auto* job = jobsToWaitFor.getUnchecked (i);
  226. if (! isJobRunning (job))
  227. jobsToWaitFor.remove (i);
  228. }
  229. if (jobsToWaitFor.size() == 0)
  230. break;
  231. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  232. return false;
  233. jobFinishedSignal.wait (20);
  234. }
  235. return true;
  236. }
  237. StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  238. {
  239. StringArray s;
  240. const ScopedLock sl (lock);
  241. for (auto* job : jobs)
  242. if (job->isActive || ! onlyReturnActiveJobs)
  243. s.add (job->getJobName());
  244. return s;
  245. }
  246. bool ThreadPool::setThreadPriorities (const int newPriority)
  247. {
  248. bool ok = true;
  249. for (auto* t : threads)
  250. if (! t->setPriority (newPriority))
  251. ok = false;
  252. return ok;
  253. }
  254. ThreadPoolJob* ThreadPool::pickNextJobToRun()
  255. {
  256. OwnedArray<ThreadPoolJob> deletionList;
  257. {
  258. const ScopedLock sl (lock);
  259. for (int i = 0; i < jobs.size(); ++i)
  260. {
  261. if (auto* job = jobs[i])
  262. {
  263. if (! job->isActive)
  264. {
  265. if (job->shouldStop)
  266. {
  267. jobs.remove (i);
  268. addToDeleteList (deletionList, job);
  269. --i;
  270. continue;
  271. }
  272. job->isActive = true;
  273. return job;
  274. }
  275. }
  276. }
  277. }
  278. return nullptr;
  279. }
  280. bool ThreadPool::runNextJob (ThreadPoolThread& thread)
  281. {
  282. if (auto* job = pickNextJobToRun())
  283. {
  284. auto result = ThreadPoolJob::jobHasFinished;
  285. thread.currentJob = job;
  286. try
  287. {
  288. result = job->runJob();
  289. }
  290. catch (...)
  291. {
  292. jassertfalse; // Your runJob() method mustn't throw any exceptions!
  293. }
  294. thread.currentJob = nullptr;
  295. OwnedArray<ThreadPoolJob> deletionList;
  296. {
  297. const ScopedLock sl (lock);
  298. if (jobs.contains (job))
  299. {
  300. job->isActive = false;
  301. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  302. {
  303. jobs.removeFirstMatchingValue (job);
  304. addToDeleteList (deletionList, job);
  305. jobFinishedSignal.signal();
  306. }
  307. else
  308. {
  309. // move the job to the end of the queue if it wants another go
  310. jobs.move (jobs.indexOf (job), -1);
  311. }
  312. }
  313. }
  314. return true;
  315. }
  316. return false;
  317. }
  318. void ThreadPool::addToDeleteList (OwnedArray<ThreadPoolJob>& deletionList, ThreadPoolJob* const job) const
  319. {
  320. job->shouldStop = true;
  321. job->pool = nullptr;
  322. if (job->shouldBeDeleted)
  323. deletionList.add (job);
  324. }