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.

344 lines
14KB

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