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.

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