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.

330 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. #ifndef JUCE_THREADPOOL_H_INCLUDED
  24. #define JUCE_THREADPOOL_H_INCLUDED
  25. class ThreadPool;
  26. class ThreadPoolThread;
  27. //==============================================================================
  28. /**
  29. A task that is executed by a ThreadPool object.
  30. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  31. its threads.
  32. The runJob() method needs to be implemented to do the task, and if the code that
  33. does the work takes a significant time to run, it must keep checking the shouldExit()
  34. method to see if something is trying to interrupt the job. If shouldExit() returns
  35. true, the runJob() method must return immediately.
  36. @see ThreadPool, Thread
  37. */
  38. class JUCE_API ThreadPoolJob
  39. {
  40. public:
  41. //==============================================================================
  42. /** Creates a thread pool job object.
  43. After creating your job, add it to a thread pool with ThreadPool::addJob().
  44. */
  45. explicit ThreadPoolJob (const String& name);
  46. /** Destructor. */
  47. virtual ~ThreadPoolJob();
  48. //==============================================================================
  49. /** Returns the name of this job.
  50. @see setJobName
  51. */
  52. String getJobName() const;
  53. /** Changes the job's name.
  54. @see getJobName
  55. */
  56. void setJobName (const String& newName);
  57. //==============================================================================
  58. /** These are the values that can be returned by the runJob() method.
  59. */
  60. enum JobStatus
  61. {
  62. jobHasFinished = 0, /**< indicates that the job has finished and can be
  63. removed from the pool. */
  64. jobNeedsRunningAgain /**< indicates that the job would like to be called
  65. again when a thread is free. */
  66. };
  67. /** Peforms the actual work that this job needs to do.
  68. Your subclass must implement this method, in which is does its work.
  69. If the code in this method takes a significant time to run, it must repeatedly check
  70. the shouldExit() method to see if something is trying to interrupt the job.
  71. If shouldExit() ever returns true, the runJob() method must return immediately.
  72. If this method returns jobHasFinished, then the job will be removed from the pool
  73. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  74. pool and will get a chance to run again as soon as a thread is free.
  75. @see shouldExit()
  76. */
  77. virtual JobStatus runJob() = 0;
  78. //==============================================================================
  79. /** Returns true if this job is currently running its runJob() method. */
  80. bool isRunning() const noexcept { return isActive; }
  81. /** Returns true if something is trying to interrupt this job and make it stop.
  82. Your runJob() method must call this whenever it gets a chance, and if it ever
  83. returns true, the runJob() method must return immediately.
  84. @see signalJobShouldExit()
  85. */
  86. bool shouldExit() const noexcept { return shouldStop; }
  87. /** Calling this will cause the shouldExit() method to return true, and the job
  88. should (if it's been implemented correctly) stop as soon as possible.
  89. @see shouldExit()
  90. */
  91. void signalJobShouldExit();
  92. //==============================================================================
  93. /** If the calling thread is being invoked inside a runJob() method, this will
  94. return the ThreadPoolJob that it belongs to.
  95. */
  96. static ThreadPoolJob* getCurrentThreadPoolJob();
  97. //==============================================================================
  98. private:
  99. friend class ThreadPool;
  100. friend class ThreadPoolThread;
  101. String jobName;
  102. ThreadPool* pool;
  103. bool shouldStop, isActive, shouldBeDeleted;
  104. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob)
  105. };
  106. //==============================================================================
  107. /**
  108. A set of threads that will run a list of jobs.
  109. When a ThreadPoolJob object is added to the ThreadPool's list, its runJob() method
  110. will be called by the next pooled thread that becomes free.
  111. @see ThreadPoolJob, Thread
  112. */
  113. class JUCE_API ThreadPool
  114. {
  115. public:
  116. //==============================================================================
  117. /** Creates a thread pool.
  118. Once you've created a pool, you can give it some jobs by calling addJob().
  119. @param numberOfThreads the number of threads to run. These will be started
  120. immediately, and will run until the pool is deleted.
  121. @param threadStackSize the size of the stack of each thread. If this value
  122. is zero then the default stack size of the OS will
  123. be used.
  124. */
  125. ThreadPool (int numberOfThreads, size_t threadStackSize = 0);
  126. /** Creates a thread pool with one thread per CPU core.
  127. Once you've created a pool, you can give it some jobs by calling addJob().
  128. If you want to specify the number of threads, use the other constructor; this
  129. one creates a pool which has one thread for each CPU core.
  130. @see SystemStats::getNumCpus()
  131. */
  132. ThreadPool();
  133. /** Destructor.
  134. This will attempt to remove all the jobs before deleting, but if you want to
  135. specify a timeout, you should call removeAllJobs() explicitly before deleting
  136. the pool.
  137. */
  138. ~ThreadPool();
  139. //==============================================================================
  140. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  141. for some kind of operation.
  142. @see ThreadPool::removeAllJobs
  143. */
  144. class JUCE_API JobSelector
  145. {
  146. public:
  147. virtual ~JobSelector() {}
  148. /** Should return true if the specified thread matches your criteria for whatever
  149. operation that this object is being used for.
  150. Any implementation of this method must be extremely fast and thread-safe!
  151. */
  152. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  153. };
  154. //==============================================================================
  155. /** Adds a job to the queue.
  156. Once a job has been added, then the next time a thread is free, it will run
  157. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  158. runJob() method, the pool will either remove the job from the pool or add it to
  159. the back of the queue to be run again.
  160. If deleteJobWhenFinished is true, then the job object will be owned and deleted by
  161. the pool when not needed - if you do this, make sure that your object's destructor
  162. is thread-safe.
  163. If deleteJobWhenFinished is false, the pointer will be used but not deleted, and
  164. the caller is responsible for making sure the object is not deleted before it has
  165. been removed from the pool.
  166. */
  167. void addJob (ThreadPoolJob* job,
  168. bool deleteJobWhenFinished);
  169. /** Tries to remove a job from the pool.
  170. If the job isn't yet running, this will simply remove it. If it is running, it
  171. will wait for it to finish.
  172. If the timeout period expires before the job finishes running, then the job will be
  173. left in the pool and this will return false. It returns true if the job is successfully
  174. stopped and removed.
  175. @param job the job to remove
  176. @param interruptIfRunning if true, then if the job is currently busy, its
  177. ThreadPoolJob::signalJobShouldExit() method will be called to try
  178. to interrupt it. If false, then if the job will be allowed to run
  179. until it stops normally (or the timeout expires)
  180. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  181. before giving up and returning false
  182. */
  183. bool removeJob (ThreadPoolJob* job,
  184. bool interruptIfRunning,
  185. int timeOutMilliseconds);
  186. /** Tries to remove all jobs from the pool.
  187. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  188. methods called to try to interrupt them
  189. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  190. before giving up and returning false
  191. @param selectedJobsToRemove if this is not a nullptr, the JobSelector object is asked to decide
  192. which jobs should be removed. If it is a nullptr, all jobs are removed
  193. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  194. expires while waiting for one or more jobs to stop
  195. */
  196. bool removeAllJobs (bool interruptRunningJobs,
  197. int timeOutMilliseconds,
  198. JobSelector* selectedJobsToRemove = nullptr);
  199. /** Returns the number of jobs currently running or queued. */
  200. int getNumJobs() const;
  201. /** Returns the number of threads assigned to this thread pool. */
  202. int getNumThreads() const;
  203. /** Returns one of the jobs in the queue.
  204. Note that this can be a very volatile list as jobs might be continuously getting shifted
  205. around in the list, and this method may return nullptr if the index is currently out-of-range.
  206. */
  207. ThreadPoolJob* getJob (int index) const;
  208. /** Returns true if the given job is currently queued or running.
  209. @see isJobRunning()
  210. */
  211. bool contains (const ThreadPoolJob* job) const;
  212. /** Returns true if the given job is currently being run by a thread.
  213. */
  214. bool isJobRunning (const ThreadPoolJob* job) const;
  215. /** Waits until a job has finished running and has been removed from the pool.
  216. This will wait until the job is no longer in the pool - i.e. until its
  217. runJob() method returns ThreadPoolJob::jobHasFinished.
  218. If the timeout period expires before the job finishes, this will return false;
  219. it returns true if the job has finished successfully.
  220. */
  221. bool waitForJobToFinish (const ThreadPoolJob* job,
  222. int timeOutMilliseconds) const;
  223. /** Returns a list of the names of all the jobs currently running or queued.
  224. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  225. */
  226. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  227. /** Changes the priority of all the threads.
  228. This will call Thread::setPriority() for each thread in the pool.
  229. May return false if for some reason the priority can't be changed.
  230. */
  231. bool setThreadPriorities (int newPriority);
  232. private:
  233. //==============================================================================
  234. Array <ThreadPoolJob*> jobs;
  235. class ThreadPoolThread;
  236. friend class ThreadPoolJob;
  237. friend class ThreadPoolThread;
  238. friend struct ContainerDeletePolicy<ThreadPoolThread>;
  239. OwnedArray<ThreadPoolThread> threads;
  240. CriticalSection lock;
  241. WaitableEvent jobFinishedSignal;
  242. bool runNextJob (ThreadPoolThread&);
  243. ThreadPoolJob* pickNextJobToRun();
  244. void addToDeleteList (OwnedArray<ThreadPoolJob>&, ThreadPoolJob*) const;
  245. void createThreads (int numThreads, size_t threadStackSize = 0);
  246. void stopThreads();
  247. // Note that this method has changed, and no longer has a parameter to indicate
  248. // whether the jobs should be deleted - see the new method for details.
  249. void removeAllJobs (bool, int, bool);
  250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool)
  251. };
  252. #endif // JUCE_THREADPOOL_H_INCLUDED