juce_ThreadPool.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. class ThreadPool::ThreadPoolThread : public Thread
  22. {
  23. public:
  24. ThreadPoolThread (ThreadPool& p)
  25. : Thread ("Pool"), currentJob (nullptr), pool (p)
  26. {
  27. }
  28. void run() override
  29. {
  30. while (! threadShouldExit())
  31. if (! pool.runNextJob (*this))
  32. wait (500);
  33. }
  34. ThreadPoolJob* volatile currentJob;
  35. ThreadPool& pool;
  36. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread)
  37. };
  38. //==============================================================================
  39. ThreadPoolJob::ThreadPoolJob (const String& name)
  40. : jobName (name), pool (nullptr),
  41. shouldStop (false), isActive (false), shouldBeDeleted (false)
  42. {
  43. }
  44. ThreadPoolJob::~ThreadPoolJob()
  45. {
  46. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  47. // to remove it first!
  48. jassert (pool == nullptr || ! pool->contains (this));
  49. }
  50. String ThreadPoolJob::getJobName() const
  51. {
  52. return jobName;
  53. }
  54. void ThreadPoolJob::setJobName (const String& newName)
  55. {
  56. jobName = newName;
  57. }
  58. void ThreadPoolJob::signalJobShouldExit()
  59. {
  60. shouldStop = true;
  61. }
  62. ThreadPoolJob* ThreadPoolJob::getCurrentThreadPoolJob()
  63. {
  64. if (ThreadPool::ThreadPoolThread* t = dynamic_cast<ThreadPool::ThreadPoolThread*> (Thread::getCurrentThread()))
  65. return t->currentJob;
  66. return nullptr;
  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, const int timeOutMs) const
  135. {
  136. if (job != nullptr)
  137. {
  138. const uint32 start = Time::getMillisecondCounter();
  139. while (contains (job))
  140. {
  141. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  142. return false;
  143. jobFinishedSignal.wait (2);
  144. }
  145. }
  146. return true;
  147. }
  148. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  149. const bool interruptIfRunning,
  150. const int timeOutMs)
  151. {
  152. bool dontWait = true;
  153. OwnedArray<ThreadPoolJob> deletionList;
  154. if (job != nullptr)
  155. {
  156. const ScopedLock sl (lock);
  157. if (jobs.contains (job))
  158. {
  159. if (job->isActive)
  160. {
  161. if (interruptIfRunning)
  162. job->signalJobShouldExit();
  163. dontWait = false;
  164. }
  165. else
  166. {
  167. jobs.removeFirstMatchingValue (job);
  168. addToDeleteList (deletionList, job);
  169. }
  170. }
  171. }
  172. return dontWait || waitForJobToFinish (job, timeOutMs);
  173. }
  174. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs, const int timeOutMs,
  175. ThreadPool::JobSelector* const selectedJobsToRemove)
  176. {
  177. Array <ThreadPoolJob*> jobsToWaitFor;
  178. {
  179. OwnedArray<ThreadPoolJob> deletionList;
  180. {
  181. const ScopedLock sl (lock);
  182. for (int i = jobs.size(); --i >= 0;)
  183. {
  184. ThreadPoolJob* const job = jobs.getUnchecked(i);
  185. if (selectedJobsToRemove == nullptr || selectedJobsToRemove->isJobSuitable (job))
  186. {
  187. if (job->isActive)
  188. {
  189. jobsToWaitFor.add (job);
  190. if (interruptRunningJobs)
  191. job->signalJobShouldExit();
  192. }
  193. else
  194. {
  195. jobs.remove (i);
  196. addToDeleteList (deletionList, job);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. const uint32 start = Time::getMillisecondCounter();
  203. for (;;)
  204. {
  205. for (int i = jobsToWaitFor.size(); --i >= 0;)
  206. {
  207. ThreadPoolJob* const job = jobsToWaitFor.getUnchecked (i);
  208. if (! isJobRunning (job))
  209. jobsToWaitFor.remove (i);
  210. }
  211. if (jobsToWaitFor.size() == 0)
  212. break;
  213. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs)
  214. return false;
  215. jobFinishedSignal.wait (20);
  216. }
  217. return true;
  218. }
  219. StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  220. {
  221. StringArray s;
  222. const ScopedLock sl (lock);
  223. for (int i = 0; i < jobs.size(); ++i)
  224. {
  225. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  226. if (job->isActive || ! onlyReturnActiveJobs)
  227. s.add (job->getJobName());
  228. }
  229. return s;
  230. }
  231. bool ThreadPool::setThreadPriorities (const int newPriority)
  232. {
  233. bool ok = true;
  234. for (int i = threads.size(); --i >= 0;)
  235. if (! threads.getUnchecked(i)->setPriority (newPriority))
  236. ok = false;
  237. return ok;
  238. }
  239. ThreadPoolJob* ThreadPool::pickNextJobToRun()
  240. {
  241. OwnedArray<ThreadPoolJob> deletionList;
  242. {
  243. const ScopedLock sl (lock);
  244. for (int i = 0; i < jobs.size(); ++i)
  245. {
  246. ThreadPoolJob* job = jobs[i];
  247. if (job != nullptr && ! job->isActive)
  248. {
  249. if (job->shouldStop)
  250. {
  251. jobs.remove (i);
  252. addToDeleteList (deletionList, job);
  253. --i;
  254. continue;
  255. }
  256. job->isActive = true;
  257. return job;
  258. }
  259. }
  260. }
  261. return nullptr;
  262. }
  263. bool ThreadPool::runNextJob (ThreadPoolThread& thread)
  264. {
  265. if (ThreadPoolJob* const job = pickNextJobToRun())
  266. {
  267. ThreadPoolJob::JobStatus result = ThreadPoolJob::jobHasFinished;
  268. thread.currentJob = job;
  269. JUCE_TRY
  270. {
  271. result = job->runJob();
  272. }
  273. JUCE_CATCH_ALL_ASSERT
  274. thread.currentJob = nullptr;
  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. return false;
  297. }
  298. void ThreadPool::addToDeleteList (OwnedArray<ThreadPoolJob>& deletionList, ThreadPoolJob* const job) const
  299. {
  300. job->shouldStop = true;
  301. job->pool = nullptr;
  302. if (job->shouldBeDeleted)
  303. deletionList.add (job);
  304. }