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.

319 lines
13KB

  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. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  22. #define __JUCE_THREADPOOL_JUCEHEADER__
  23. #include "juce_Thread.h"
  24. #include "../text/juce_StringArray.h"
  25. #include "../containers/juce_Array.h"
  26. #include "../containers/juce_OwnedArray.h"
  27. class ThreadPool;
  28. class ThreadPoolThread;
  29. //==============================================================================
  30. /**
  31. A task that is executed by a ThreadPool object.
  32. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  33. its threads.
  34. The runJob() method needs to be implemented to do the task, and if the code that
  35. does the work takes a significant time to run, it must keep checking the shouldExit()
  36. method to see if something is trying to interrupt the job. If shouldExit() returns
  37. true, the runJob() method must return immediately.
  38. @see ThreadPool, Thread
  39. */
  40. class JUCE_API ThreadPoolJob
  41. {
  42. public:
  43. //==============================================================================
  44. /** Creates a thread pool job object.
  45. After creating your job, add it to a thread pool with ThreadPool::addJob().
  46. */
  47. explicit ThreadPoolJob (const String& name);
  48. /** Destructor. */
  49. virtual ~ThreadPoolJob();
  50. //==============================================================================
  51. /** Returns the name of this job.
  52. @see setJobName
  53. */
  54. String getJobName() const;
  55. /** Changes the job's name.
  56. @see getJobName
  57. */
  58. void setJobName (const String& newName);
  59. //==============================================================================
  60. /** These are the values that can be returned by the runJob() method.
  61. */
  62. enum JobStatus
  63. {
  64. jobHasFinished = 0, /**< indicates that the job has finished and can be
  65. removed from the pool. */
  66. jobNeedsRunningAgain /**< indicates that the job would like to be called
  67. again when a thread is free. */
  68. };
  69. /** Peforms the actual work that this job needs to do.
  70. Your subclass must implement this method, in which is does its work.
  71. If the code in this method takes a significant time to run, it must repeatedly check
  72. the shouldExit() method to see if something is trying to interrupt the job.
  73. If shouldExit() ever returns true, the runJob() method must return immediately.
  74. If this method returns jobHasFinished, then the job will be removed from the pool
  75. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  76. pool and will get a chance to run again as soon as a thread is free.
  77. @see shouldExit()
  78. */
  79. virtual JobStatus runJob() = 0;
  80. //==============================================================================
  81. /** Returns true if this job is currently running its runJob() method. */
  82. bool isRunning() const noexcept { return isActive; }
  83. /** Returns true if something is trying to interrupt this job and make it stop.
  84. Your runJob() method must call this whenever it gets a chance, and if it ever
  85. returns true, the runJob() method must return immediately.
  86. @see signalJobShouldExit()
  87. */
  88. bool shouldExit() const noexcept { return shouldStop; }
  89. /** Calling this will cause the shouldExit() method to return true, and the job
  90. should (if it's been implemented correctly) stop as soon as possible.
  91. @see shouldExit()
  92. */
  93. void signalJobShouldExit();
  94. //==============================================================================
  95. private:
  96. friend class ThreadPool;
  97. friend class ThreadPoolThread;
  98. String jobName;
  99. ThreadPool* pool;
  100. bool shouldStop, isActive, shouldBeDeleted;
  101. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob)
  102. };
  103. //==============================================================================
  104. /**
  105. A set of threads that will run a list of jobs.
  106. When a ThreadPoolJob object is added to the ThreadPool's list, its runJob() method
  107. will be called by the next pooled thread that becomes free.
  108. @see ThreadPoolJob, Thread
  109. */
  110. class JUCE_API ThreadPool
  111. {
  112. public:
  113. //==============================================================================
  114. /** Creates a thread pool.
  115. Once you've created a pool, you can give it some jobs by calling addJob().
  116. @param numberOfThreads the number of threads to run. These will be started
  117. immediately, and will run until the pool is deleted.
  118. */
  119. ThreadPool (int numberOfThreads);
  120. /** Creates a thread pool with one thread per CPU core.
  121. Once you've created a pool, you can give it some jobs by calling addJob().
  122. If you want to specify the number of threads, use the other constructor; this
  123. one creates a pool which has one thread for each CPU core.
  124. @see SystemStats::getNumCpus()
  125. */
  126. ThreadPool();
  127. /** Destructor.
  128. This will attempt to remove all the jobs before deleting, but if you want to
  129. specify a timeout, you should call removeAllJobs() explicitly before deleting
  130. the pool.
  131. */
  132. ~ThreadPool();
  133. //==============================================================================
  134. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  135. for some kind of operation.
  136. @see ThreadPool::removeAllJobs
  137. */
  138. class JUCE_API JobSelector
  139. {
  140. public:
  141. virtual ~JobSelector() {}
  142. /** Should return true if the specified thread matches your criteria for whatever
  143. operation that this object is being used for.
  144. Any implementation of this method must be extremely fast and thread-safe!
  145. */
  146. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  147. };
  148. //==============================================================================
  149. /** Adds a job to the queue.
  150. Once a job has been added, then the next time a thread is free, it will run
  151. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  152. runJob() method, the pool will either remove the job from the pool or add it to
  153. the back of the queue to be run again.
  154. If deleteJobWhenFinished is true, then the job object will be owned and deleted by
  155. the pool when not needed - if you do this, make sure that your object's destructor
  156. is thread-safe.
  157. If deleteJobWhenFinished is false, the pointer will be used but not deleted, and
  158. the caller is responsible for making sure the object is not deleted before it has
  159. been removed from the pool.
  160. */
  161. void addJob (ThreadPoolJob* job,
  162. bool deleteJobWhenFinished);
  163. /** Tries to remove a job from the pool.
  164. If the job isn't yet running, this will simply remove it. If it is running, it
  165. will wait for it to finish.
  166. If the timeout period expires before the job finishes running, then the job will be
  167. left in the pool and this will return false. It returns true if the job is sucessfully
  168. stopped and removed.
  169. @param job the job to remove
  170. @param interruptIfRunning if true, then if the job is currently busy, its
  171. ThreadPoolJob::signalJobShouldExit() method will be called to try
  172. to interrupt it. If false, then if the job will be allowed to run
  173. until it stops normally (or the timeout expires)
  174. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  175. before giving up and returning false
  176. */
  177. bool removeJob (ThreadPoolJob* job,
  178. bool interruptIfRunning,
  179. int timeOutMilliseconds);
  180. /** Tries to remove all jobs from the pool.
  181. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  182. methods called to try to interrupt them
  183. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  184. before giving up and returning false
  185. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  186. jobs should be removed. If it is zero, all jobs are removed
  187. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  188. expires while waiting for one or more jobs to stop
  189. */
  190. bool removeAllJobs (bool interruptRunningJobs,
  191. int timeOutMilliseconds,
  192. JobSelector* selectedJobsToRemove = nullptr);
  193. /** Returns the number of jobs currently running or queued.
  194. */
  195. int getNumJobs() const;
  196. /** Returns one of the jobs in the queue.
  197. Note that this can be a very volatile list as jobs might be continuously getting shifted
  198. around in the list, and this method may return 0 if the index is currently out-of-range.
  199. */
  200. ThreadPoolJob* getJob (int index) const;
  201. /** Returns true if the given job is currently queued or running.
  202. @see isJobRunning()
  203. */
  204. bool contains (const ThreadPoolJob* job) const;
  205. /** Returns true if the given job is currently being run by a thread.
  206. */
  207. bool isJobRunning (const ThreadPoolJob* job) const;
  208. /** Waits until a job has finished running and has been removed from the pool.
  209. This will wait until the job is no longer in the pool - i.e. until its
  210. runJob() method returns ThreadPoolJob::jobHasFinished.
  211. If the timeout period expires before the job finishes, this will return false;
  212. it returns true if the job has finished successfully.
  213. */
  214. bool waitForJobToFinish (const ThreadPoolJob* job,
  215. int timeOutMilliseconds) const;
  216. /** Returns a list of the names of all the jobs currently running or queued.
  217. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  218. */
  219. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  220. /** Changes the priority of all the threads.
  221. This will call Thread::setPriority() for each thread in the pool.
  222. May return false if for some reason the priority can't be changed.
  223. */
  224. bool setThreadPriorities (int newPriority);
  225. private:
  226. //==============================================================================
  227. Array <ThreadPoolJob*> jobs;
  228. class ThreadPoolThread;
  229. friend class ThreadPoolThread;
  230. friend class OwnedArray <ThreadPoolThread>;
  231. OwnedArray <ThreadPoolThread> threads;
  232. CriticalSection lock;
  233. WaitableEvent jobFinishedSignal;
  234. bool runNextJob();
  235. ThreadPoolJob* pickNextJobToRun();
  236. void addToDeleteList (OwnedArray<ThreadPoolJob>&, ThreadPoolJob*) const;
  237. void createThreads (int numThreads);
  238. void stopThreads();
  239. // Note that this method has changed, and no longer has a parameter to indicate
  240. // whether the jobs should be deleted - see the new method for details.
  241. void removeAllJobs (bool, int, bool);
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool)
  243. };
  244. #endif // __JUCE_THREADPOOL_JUCEHEADER__