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.

426 lines
11KB

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