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.

318 lines
13KB

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