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.

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