OpenShot Library | OpenShotAudio  0.2.2
juce_Thread.h
1 
2 /** @weakgroup juce_core-threads
3  * @{
4  */
5 /*
6  ==============================================================================
7 
8  This file is part of the JUCE library.
9  Copyright (c) 2017 - ROLI Ltd.
10 
11  JUCE is an open source library subject to commercial or open-source
12  licensing.
13 
14  The code included in this file is provided under the terms of the ISC license
15  http://www.isc.org/downloads/software-support-policy/isc-license. Permission
16  To use, copy, modify, and/or distribute this software for any purpose with or
17  without fee is hereby granted provided that the above copyright notice and
18  this permission notice appear in all copies.
19 
20  JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
21  EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
22  DISCLAIMED.
23 
24  ==============================================================================
25 */
26 
27 namespace juce
28 {
29 
30 //==============================================================================
31 /**
32  Encapsulates a thread.
33 
34  Subclasses derive from Thread and implement the run() method, in which they
35  do their business. The thread can then be started with the startThread() method
36  and controlled with various other methods.
37 
38  This class also contains some thread-related static methods, such
39  as sleep(), yield(), getCurrentThreadId() etc.
40 
41  @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
42  MessageManagerLock
43 
44  @tags{Core}
45 */
47 {
48 public:
49  //==============================================================================
50  /**
51  Creates a thread.
52 
53  When first created, the thread is not running. Use the startThread()
54  method to start it.
55 
56  @param threadName The name of the thread which typically appears in
57  debug logs and profiles.
58  @param threadStackSize The size of the stack of the thread. If this value
59  is zero then the default stack size of the OS will
60  be used.
61  */
62  explicit Thread (const String& threadName, size_t threadStackSize = 0);
63 
64  /** Destructor.
65 
66  You must never attempt to delete a Thread object while it's still running -
67  always call stopThread() and make sure your thread has stopped before deleting
68  the object. Failing to do so will throw an assertion, and put you firmly into
69  undefined behaviour territory.
70  */
71  virtual ~Thread();
72 
73  //==============================================================================
74  /** Must be implemented to perform the thread's actual code.
75 
76  Remember that the thread must regularly check the threadShouldExit()
77  method whilst running, and if this returns true it should return from
78  the run() method as soon as possible to avoid being forcibly killed.
79 
80  @see threadShouldExit, startThread
81  */
82  virtual void run() = 0;
83 
84  //==============================================================================
85  /** Starts the thread running.
86 
87  This will cause the thread's run() method to be called by a new thread.
88  If this thread is already running, startThread() won't do anything.
89 
90  @see stopThread
91  */
92  void startThread();
93 
94  /** Starts the thread with a given priority.
95 
96  Launches the thread with a given priority, where 0 = lowest, 10 = highest.
97  If the thread is already running, its priority will be changed.
98 
99  @see startThread, setPriority, realtimeAudioPriority
100  */
101  void startThread (int priority);
102 
103  /** Attempts to stop the thread running.
104 
105  This method will cause the threadShouldExit() method to return true
106  and call notify() in case the thread is currently waiting.
107 
108  Hopefully the thread will then respond to this by exiting cleanly, and
109  the stopThread method will wait for a given time-period for this to
110  happen.
111 
112  If the thread is stuck and fails to respond after the timeout, it gets
113  forcibly killed, which is a very bad thing to happen, as it could still
114  be holding locks, etc. which are needed by other parts of your program.
115 
116  @param timeOutMilliseconds The number of milliseconds to wait for the
117  thread to finish before killing it by force. A negative
118  value in here will wait forever.
119  @returns true if the thread was cleanly stopped before the timeout, or false
120  if it had to be killed by force.
121  @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
122  */
123  bool stopThread (int timeOutMilliseconds);
124 
125  //==============================================================================
126  /** Invokes a lambda or function on its own thread.
127 
128  This will spin up a Thread object which calls the function and then exits.
129  Bear in mind that starting and stopping a thread can be a fairly heavyweight
130  operation, so you might prefer to use a ThreadPool if you're kicking off a lot
131  of short background tasks.
132 
133  Also note that using an anonymous thread makes it very difficult to interrupt
134  the function when you need to stop it, e.g. when your app quits. So it's up to
135  you to deal with situations where the function may fail to stop in time.
136  */
137  static void launch (std::function<void()> functionToRun);
138 
139  //==============================================================================
140  /** Returns true if the thread is currently active */
141  bool isThreadRunning() const;
142 
143  /** Sets a flag to tell the thread it should stop.
144 
145  Calling this means that the threadShouldExit() method will then return true.
146  The thread should be regularly checking this to see whether it should exit.
147 
148  If your thread makes use of wait(), you might want to call notify() after calling
149  this method, to interrupt any waits that might be in progress, and allow it
150  to reach a point where it can exit.
151 
152  @see threadShouldExit, waitForThreadToExit
153  */
154  void signalThreadShouldExit();
155 
156  /** Checks whether the thread has been told to stop running.
157 
158  Threads need to check this regularly, and if it returns true, they should
159  return from their run() method at the first possible opportunity.
160 
161  @see signalThreadShouldExit, currentThreadShouldExit
162  */
163  bool threadShouldExit() const;
164 
165  /** Checks whether the current thread has been told to stop running.
166  On the message thread, this will always return false, otherwise
167  it will return threadShouldExit() called on the current thread.
168 
169  @see threadShouldExit
170  */
171  static bool currentThreadShouldExit();
172 
173  /** Waits for the thread to stop.
174  This will wait until isThreadRunning() is false or until a timeout expires.
175 
176  @param timeOutMilliseconds the time to wait, in milliseconds. If this value
177  is less than zero, it will wait forever.
178  @returns true if the thread exits, or false if the timeout expires first.
179  */
180  bool waitForThreadToExit (int timeOutMilliseconds) const;
181 
182  //==============================================================================
183  /** Used to receive callbacks for thread exit calls */
185  {
186  public:
187  virtual ~Listener() = default;
188 
189  /** Called if Thread::signalThreadShouldExit was called.
190  @see Thread::threadShouldExit, Thread::addListener, Thread::removeListener
191  */
192  virtual void exitSignalSent() = 0;
193  };
194 
195  /** Add a listener to this thread which will receive a callback when
196  signalThreadShouldExit was called on this thread.
197 
198  @see signalThreadShouldExit, removeListener
199  */
200  void addListener (Listener*);
201 
202  /** Removes a listener added with addListener. */
203  void removeListener (Listener*);
204 
205  //==============================================================================
206  /** Special realtime audio thread priority
207 
208  This priority will create a high-priority thread which is best suited
209  for realtime audio processing.
210 
211  Currently, this priority is identical to priority 9, except when building
212  for Android with OpenSL/Oboe support.
213 
214  In this case, JUCE will ask OpenSL/Oboe to construct a super high priority thread
215  specifically for realtime audio processing.
216 
217  Note that this priority can only be set **before** the thread has
218  started. Switching to this priority, or from this priority to a different
219  priority, is not supported under Android and will assert.
220 
221  For best performance this thread should yield at regular intervals
222  and not call any blocking APIs.
223 
224  @see startThread, setPriority, sleep, WaitableEvent
225  */
226  enum
227  {
228  realtimeAudioPriority = -1
229  };
230 
231  /** Changes the thread's priority.
232 
233  May return false if for some reason the priority can't be changed.
234 
235  @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
236  of 5 is normal.
237  @see realtimeAudioPriority
238  */
239  bool setPriority (int priority);
240 
241  /** Changes the priority of the caller thread.
242 
243  Similar to setPriority(), but this static method acts on the caller thread.
244  May return false if for some reason the priority can't be changed.
245 
246  @see setPriority
247  */
248  static bool setCurrentThreadPriority (int priority);
249 
250  //==============================================================================
251  /** Sets the affinity mask for the thread.
252 
253  This will only have an effect next time the thread is started - i.e. if the
254  thread is already running when called, it'll have no effect.
255 
256  @see setCurrentThreadAffinityMask
257  */
258  void setAffinityMask (uint32 affinityMask);
259 
260  /** Changes the affinity mask for the caller thread.
261 
262  This will change the affinity mask for the thread that calls this static method.
263 
264  @see setAffinityMask
265  */
266  static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
267 
268  //==============================================================================
269  /** Suspends the execution of the current thread until the specified timeout period
270  has elapsed (note that this may not be exact).
271 
272  The timeout period must not be negative and whilst sleeping the thread cannot
273  be woken up so it should only be used for short periods of time and when other
274  methods such as using a WaitableEvent or CriticalSection are not possible.
275  */
276  static void JUCE_CALLTYPE sleep (int milliseconds);
277 
278  /** Yields the current thread's CPU time-slot and allows a new thread to run.
279 
280  If there are no other threads of equal or higher priority currently running then
281  this will return immediately and the current thread will continue to run.
282  */
283  static void JUCE_CALLTYPE yield();
284 
285  //==============================================================================
286  /** Suspends the execution of this thread until either the specified timeout period
287  has elapsed, or another thread calls the notify() method to wake it up.
288 
289  A negative timeout value means that the method will wait indefinitely.
290 
291  @returns true if the event has been signalled, false if the timeout expires.
292  */
293  bool wait (int timeOutMilliseconds) const;
294 
295  /** Wakes up the thread.
296 
297  If the thread has called the wait() method, this will wake it up.
298 
299  @see wait
300  */
301  void notify() const;
302 
303  //==============================================================================
304  /** A value type used for thread IDs.
305 
306  @see getCurrentThreadId(), getThreadId()
307  */
308  using ThreadID = void*;
309 
310  /** Returns an id that identifies the caller thread.
311 
312  To find the ID of a particular thread object, use getThreadId().
313 
314  @returns a unique identifier that identifies the calling thread.
315  @see getThreadId
316  */
317  static ThreadID JUCE_CALLTYPE getCurrentThreadId();
318 
319  /** Finds the thread object that is currently running.
320 
321  Note that the main UI thread (or other non-JUCE threads) don't have a Thread
322  object associated with them, so this will return nullptr.
323  */
324  static Thread* JUCE_CALLTYPE getCurrentThread();
325 
326  /** Returns the ID of this thread.
327 
328  That means the ID of this thread object - not of the thread that's calling the method.
329  This can change when the thread is started and stopped, and will be invalid if the
330  thread's not actually running.
331 
332  @see getCurrentThreadId
333  */
334  ThreadID getThreadId() const noexcept;
335 
336  /** Returns the name of the thread. This is the name that gets set in the constructor. */
337  const String& getThreadName() const noexcept { return threadName; }
338 
339  /** Changes the name of the caller thread.
340 
341  Different OSes may place different length or content limits on this name.
342  */
343  static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
344 
345  #if JUCE_ANDROID || defined (DOXYGEN)
346  //==============================================================================
347  /** Initialises the JUCE subsystem for projects not created by the Projucer
348 
349  On Android, JUCE needs to be initialised once before it is used. The Projucer
350  will automatically generate the necessary java code to do this. However, if
351  you are using JUCE without the Projucer or are creating a library made with
352  JUCE intended for use in non-JUCE apks, then you must call this method
353  manually once on apk startup.
354 
355  You can call this method from C++ or directly from java by calling the
356  following java method:
357 
358  @code
359  com.roli.juce.Java.initialiseJUCE (myContext);
360  @endcode
361 
362  Note that the above java method is only available in Android Studio projects
363  created by the Projucer. If you need to call this from another type of project
364  then you need to add the following java file to
365  your project:
366 
367  @code
368  package com.roli.juce;
369 
370  public class Java
371  {
372  static { System.loadLibrary ("juce_jni"); }
373  public native static void initialiseJUCE (Context context);
374  }
375  @endcode
376 
377  @param jniEnv this is a pointer to JNI's JNIEnv variable. Any callback
378  from Java into C++ will have this passed in as it's first
379  parameter.
380  @param jContext this is a jobject referring to your app/service/receiver/
381  provider's Context. JUCE needs this for many of it's internal
382  functions.
383  */
384  static void initialiseJUCE (void* jniEnv, void* jContext);
385  #endif
386 
387 private:
388  //==============================================================================
389  const String threadName;
390  Atomic<void*> threadHandle { nullptr };
391  Atomic<ThreadID> threadId = {};
392  CriticalSection startStopLock;
393  WaitableEvent startSuspensionEvent, defaultEvent;
394  int threadPriority = 5;
395  size_t threadStackSize;
396  uint32 affinityMask = 0;
397  bool deleteOnThreadEnd = false;
398  Atomic<int32> shouldExit { 0 };
400 
401  #if JUCE_ANDROID
402  bool isAndroidRealtimeThread = false;
403  #endif
404 
405  #ifndef DOXYGEN
406  friend void JUCE_API juce_threadEntryPoint (void*);
407  #endif
408 
409  void launchThread();
410  void closeThreadHandle();
411  void killThread();
412  void threadEntryPoint();
413  static bool setThreadPriority (void*, int);
414 
415  JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
416 };
417 
418 } // namespace juce
419 
420 /** @}*/
A simple wrapper around std::atomic.
Definition: juce_Atomic.h:45
#define JUCE_API
This macro is added to all JUCE public class declarations.
void * ThreadID
A value type used for thread IDs.
Definition: juce_Thread.h:308
Allows threads to wait for events triggered by other threads.
The JUCE String class!
Definition: juce_String.h:42
Holds a set of objects and can invoke a member function callback on each object in the set with a sin...
Used to receive callbacks for thread exit calls.
Definition: juce_Thread.h:184
Encapsulates a thread.
Definition: juce_Thread.h:46
A re-entrant mutex.