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.

433 lines
11KB

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