HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_Thread.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: UT_Thread.h ( UT Library, C++)
7  *
8  * COMMENTS: Generic thread class.
9  * The owner of the thread can do things like:
10  *
11  * killThread() - Stop execution of thread
12  * waitThread() - Wait until thread finishes execution
13  * suspendThread() - Suspend execution of thread
14  * restartThread() - Restart a stopped thread
15  *
16  * TODO: It might be nice to have a way to get the exit status of a thread.
17  */
18 
19 #ifndef __UT_Thread__
20 #define __UT_Thread__
21 
22 #include "UT_API.h"
23 #include "UT_Array.h"
24 #include "UT_Assert.h"
25 #include "UT_UniquePtr.h"
26 
27 #include <SYS/SYS_Deprecated.h>
29 #include <SYS/SYS_Types.h>
30 
31 #include <stdlib.h>
32 
33 #include <thread>
34 #include <tuple>
35 
36 #if defined(WIN32)
37 # include <intrin.h>
38  typedef int ut_thread_id_t;
39 #elif defined(USE_PTHREADS)
40 # include <sched.h>
41 # include <pthread.h>
42  typedef pthread_t ut_thread_id_t;
43 #else
44  #error Unsupported Platform for UT_Thread
45 #endif
46 
47 #define UT_INVALID_THREAD_ID ((ut_thread_id_t)0)
48 
49 // some stack size defines
50 #define UT_THREAD_DEFAULT_STACK_SIZE (8U*1024U*1024U)
51 #define UT_THREAD_SMALL_STACK_SIZE (1U*1024U*1024U)
52 
53 typedef void *(*UTthreadFunc)(void*);
54 
55 // forward declarations
56 class UT_TaskScope;
57 
59 {
60 public:
61  // The destructor will wait until the thread is idle before it completes
62  // If you wish to kill the thread, call killThread() first.
63  virtual ~UT_Thread();
64 
65  UT_Thread(const UT_Thread &) = delete;
66  UT_Thread &operator=(const UT_Thread &) = delete;
67 
68  // This enum specifies the current state for a persistent thread. The
69  // thread will typically be running or idle. If the thread is idle, it's
70  // behaviour will be determined by the SpinState.
71  enum State
72  {
74  ThreadRunning
75  };
76 
77  // // The thread status determines how the thread will behave once the
78  // callback function is completed:
79  // ThreadSingleRun - The thread cannot be restarted
80  // ThreadLowUsage - The thread will yield cycles while idle
81  //
82  enum SpinMode
83  {
86  };
87 
88  /// Allocate a new thread
89  /// @param spin_mode Use ThreadSingleRun to have it exit when the thread
90  /// callback is finished. Otherwise, ThreadLowUsage
91  /// will cause the thread to loop back and wait for
92  /// more startThread() calls to run different thread
93  /// callbacks in the same thread.
94  static UT_Thread *allocThread(SpinMode spin_mode);
95 
96  static int getNumProcessors();
97 
98  /// This is only valid in debug builds
99  static int activeThreadCount();
100 
101  /// Reset the number of threads that is used by Houdini. This will reread
102  /// the HOUDINI_MAXTHREADS setting.
103  /// @note There should be no active tasks when this is called.
104  /// @note Only call this from the MAIN THREAD!
105  static void resetNumProcessors();
106 
107  // getMyThreadId() is inlined for speed if we're using pthreads.
108 #if defined(USE_PTHREADS)
109  static ut_thread_id_t getMyThreadId() { return pthread_self(); }
110 #else
111  static ut_thread_id_t getMyThreadId();
112 #endif
113 
114  static ut_thread_id_t getMainThreadId();
115  static int getMainSequentialThreadId();
116  static inline int isMainThread()
117  {
118  return getMyThreadId() == getMainThreadId();
119  }
120 
121  /// Returns true if the current thread is a UT_Thread.
122  /// Returns false if the current thread is either the main thread
123  /// or a TBB thread.
124  static bool isUTThreadCurrent();
125 
126  /// Returns true iff the current thread is allowed to create more tasks.
127  /// This is sometimes disabled, to avoid needing to create a UT_TaskArena
128  /// for small cases that won't get much benefit from threading.
129  /// This should be checked by anything using tbb::parallel_for,
130  /// tbb::parallel_invoke, or anything else creating TBB tasks.
131  static bool isThreadingEnabled();
132 
133  /// This is used to disable (false) threading for the current thread,
134  /// to avoid needing to create a UT_TaskArena for small cases that won't
135  /// get much benefit from threading. It returns if it was enabled before.
136  /// It is also used to re-enable (true) threading for the current thread.
137  static bool setThreadingEnabled(bool will_be_enabled);
138 
140  {
141  public:
143  : myPreviouslyEnabled(setThreadingEnabled(false))
144  {}
146  {
147  if (myPreviouslyEnabled)
148  setThreadingEnabled(true);
149  }
150  private:
151  const bool myPreviouslyEnabled;
152  };
153 
154  // CPU pauses the task for a given number of cycles
155  static inline void pause(uint cycles)
156  {
157  for(uint i = 0; i < cycles; i++)
158 #if defined(USE_PTHREADS)
159 #if defined(ARM64)
160  __asm__ __volatile__("yield;");
161 #else
162  __asm__ __volatile__("pause;");
163 #endif
164 #else
165  _mm_pause();
166 #endif
167  }
168  // Yields the task to the scheduler.
169 #if defined(USE_PTHREADS)
170  static inline void yield(bool higher_only=false)
171  {
172  if (higher_only)
173  {
174  ::sched_yield();
175  }
176  else
177  {
178  // Sleep for 100ns. That's 10,000,000 sleep
179  // cycles a second (in case you don't have a
180  // calculator :-)
181  struct timespec ts = {0,100};
182  ::nanosleep(&ts, 0);
183  }
184  }
185 #else
186  static void yield(bool higher_only=false);
187 #endif
188 
189  /// This function has been deprecated. Use SYS_SequentialThreadIndex::get()
190  /// or SYSgetSTID instead.
191  static int SYS_DEPRECATED(12.5) getMySequentialThreadIndex()
192  { return SYS_SequentialThreadIndex::get(); }
193 
194  /// Configure the global number of tasks used by the system
195  /// - The default value of 0 uses the number of logical cores on the system
196  /// - A negative value wraps it from the number of logical cores.
197  /// eg. -1 will use all cores except for 1.
198  /// - If the negative value exceeds the number of logical cores, it is
199  /// clamped to a value of 1.
200  /// @note Only call this in the main thread when there are no tasks active.
201  /// @note This function is NOT thread-safe.
202  static void configureMaxThreads(int maxthreads = 0);
203 
204  /// Configure the default stack size for threads
205  /// - A value of 0 uses the stack size of the main thread
206  /// - A value larger than 0 will use that specific stack size
207  /// @note Only call this in the main thread when there are no tasks active.
208  /// @note This function is NOT thread-safe.
209  static void configureThreadStackSize(int stacksize);
210 
211  /// Return the current running thread's stack size
212  static int getCurrentThreadStackSize();
213 
214  /// Sets the current thread to minimum priority according to the rules
215  /// of the platform. This function fails if called on a thread that is
216  /// not a running UT_Thread.
217  /// Returns true if the operation was successful, otherwise returns false.
218  static bool minimizeThisThreadPriority();
219 
220 #if defined(MBSD)
221  /// Sets the quality of service (QoS) class of a thread. This is used by
222  /// the macOS scheduler to prioritize certain tasks.
223  /// @note Calling this is optional, however if it is called, it must be
224  /// called before startThread()
225  /// @note This method is only available on macOS
226  void setQoS(qos_class_t qos);
227 
228  /// Returns the quality of service (QoS) class of a thread.
229  /// @note This method is only available on macOS
230  /// @see setQoS()
231  qos_class_t getQoS() const;
232 #endif
233 
235  {
236  public:
239 
240  DisableGlobalControl(const DisableGlobalControl &) = delete;
242  };
243 
244  // Start the thread running. If the thread is not in idle state, the
245  // thread will wait until it's in idle before starting. If the thread
246  // doesn't exist yet, it will be created.
247  virtual bool startThread(UTthreadFunc func, void *data,
248  int stacksize) = 0;
249 
250  // Use the global thread stack size set by configureMaxThreads()
251  bool startThread(UTthreadFunc func, void *data);
252 
253  // This method is called when the thread function is first entered.
254  // By default it does nothing but some sub-classes may need this.
255  virtual void threadStarted();
256 
257  // This method is called when the thread function is returned from.
258  // By default it sets the state to idle.
259  virtual void threadEnded();
260 
261 
262  // Some thread architectures have very expensive resources (i.e. sproc()
263  // threads). While these threads spin (are idle), they consume system
264  // resources. This method will let the user know whether the threads are
265  // resource hogs (so that if they spin for a long time, they could
266  // possibley be cleaned up).
267  virtual int isResourceHog() const;
268 
269  // For persistent threads (which get restarted)
270  virtual State getState();
271  virtual SpinMode getSpinMode();
272  virtual void waitForState(State desired) = 0;
273  virtual void setSpinMode(SpinMode spin_mode);
274 
275  // Terminate the thread process
276  virtual void killThread() = 0;
277 
278  // If it's possible to perform these tasks, the return code will be 1. If
279  // not, the return code will be 0.
280  virtual int suspendThread() = 0;
281  virtual int restartThread() = 0;
282 
283  int isActive()
284  { return waitThread(0); }
285 
286  /// NOTE: This level doesn't own any data apart from itself.
287  virtual int64 getMemoryUsage(bool inclusive) const = 0;
288 
289 protected:
290  // System dependent internal functions.
291  // waitThread() returns 1 if the thread is still active (i.e. exists) and
292  // should return 0 if the thread doesn't exist. If waitThread detects
293  // that the thread no longer exists, it should do appropriate cleanup.
294  virtual int waitThread(int block=1) = 0;
295 
296  // Quick check to see that the thread is really active
297  virtual int isValid();
298 
299  // This method can be used to kill an idle process.
300  void killIdle();
301 
302  static void *threadWrapper(void *data);
303 
304  // Internally used to change the state safely.
305  virtual void setState(State state) = 0;
306 
307  volatile State myState;
310  void *myCBData;
311 
313 
314 #if defined(MBSD)
315  // The quality of service (QoS) of this thread for the macOS scheduler
316  qos_class_t myQoS;
317 #endif
318 
319  UT_Thread(SpinMode spin_mode);
320 
321 private:
322  friend class UT_SubSystem;
323 
324  static void onExit_();
325 };
326 
327 // For debugging, the following uses a single thread (i.e. is not
328 // multi-threaded)
330 {
331 public:
332  UT_NullThread();
333  ~UT_NullThread() override;
334 
335  UT_NullThread(const UT_NullThread &) = delete;
336  UT_NullThread &operator=(const UT_NullThread &) = delete;
337 
338  bool startThread(UTthreadFunc func, void *data,
339  int stacksize) override;
340  void killThread() override;
341  int waitThread(int block) override;
342  void waitForState(State) override;
343 
344  int suspendThread() override;
345  int restartThread() override;
346 
347  int64 getMemoryUsage(bool inclusive) const override
348  {
349  int64 mem = inclusive ? sizeof(*this) : 0;
350  // NOTE: We don't know how much memory Windows uses,
351  // so we can't count it.
352  return mem;
353  }
354 
355 protected:
356  void setState(State state) override;
357 };
358 
359 
361 {
362 public:
363  UT_ThreadSet(int nthreads=-1, int null_thread_if_1_cpu = 0);
364  ~UT_ThreadSet();
365 
366  UT_ThreadSet(const UT_ThreadSet &) = delete;
367  UT_ThreadSet &operator=(const UT_ThreadSet &) = delete;
368 
370  {
371  myFunc = func;
372  }
373  void setUserData(void *user_data_array, size_t structlen)
374  {
375  myUserData = user_data_array;
376  myUserDataInc = structlen;
377  }
378  void setUserData(void *user_data)
379  {
380  myUserData = user_data;
381  myUserDataInc = 0;
382  }
383 
384  void reuse(UT_Thread::SpinMode spin_mode);
385  void go();
386  int wait(int block=1);
387 
388  int getNumThreads() const { return myThreadCount; }
389  UT_Thread *getThread(int which);
390  UT_Thread *operator[](int which)
391  {
392  UT_ASSERT_P(which < myThreadCount);
393  return myThreads[which];
394  }
395 
396 protected:
400  void *myUserData;
402 };
403 
405 {
406 public:
408  {
409  NON_BLOCKING = 0, // Only assign thread if one is available
410  BLOCKING = 1, // Block until a thread is free.
411  DYNAMIC = 2 // If no threads are availble, create a new one.
412  };
413 
414  // similar to UT_ThreadSet, but a bit simpler. Called UT_ThreadFarm
415  // because it farms out the next available thread. You also don't need to
416  // match the number of data chunks to the number of threads.
417  // ie.
418  // farm = new UT_ThreadFarm(4);
419  // while(!done) {
420  // thread = farm->nextThread();
421  // thread->startThread(entrypoint, mydata);
422  // }
423  // farm->wait();
424 
425  UT_ThreadFarm(int nthreads=-1);
426  ~UT_ThreadFarm();
427 
428  UT_ThreadFarm(const UT_ThreadFarm &) = delete;
429  UT_ThreadFarm &operator=(const UT_ThreadFarm &) = delete;
430 
431  // waits for the next available thread, (or returns null if none are
432  // available and block = 0). thread_index will contain the thread index
433  // if you pass it a non-null pointer.
434  UT_Thread *nextThread(int *thread_index =0,
435  AssignmentStyle style = BLOCKING);
436 
437  // waits until all threads are finished (or, returns 0 if not finished and
438  // block = 0).
439  int wait(int block = 1);
440 
441  // deletes threads in the thread farm. if kill=1 the threads are killed before
442  // cleanup, otherwise wait(1) is called.
443  void cleanup(int kill = 0);
444 
445  int getEntries() const { return myThreadCount; }
447  {
448  UT_ASSERT_P(index < myThreadCount);
449  return myThreads[index];
450  }
451 
452 protected:
453  void addThreads(int thread_count);
454 
457 };
458 
459 // Gradual backoff when there's thread contention.
461 {
462 public:
463  UT_ThreadBackoff() : myCycles(1) {}
464 
465  static const uint cycles_for_noop = 4;
466  static const uint cycles_for_pause = cycles_for_noop * 4;
467  static const uint cycles_for_yield_higher = cycles_for_pause * 2;
468  static const uint cycles_for_yield_all = cycles_for_yield_higher * 2;
469 
470  // Same thresholds as hboost::detail::yield(), but different behaviour
471  void wait()
472  {
473  if (myCycles > cycles_for_yield_all)
474  {
475  // Yield the thread completely, to any and all comers.
476  UT_Thread::yield(false);
477  return;
478  }
479 
480  if (myCycles <= cycles_for_noop)
481  {
482  // Noop.
483  }
484  else if (myCycles <= cycles_for_pause)
485  {
486  UT_Thread::pause(myCycles);
487  }
488  else if (myCycles <= cycles_for_yield_higher)
489  {
490  UT_Thread::yield(true);
491  }
492  myCycles += (myCycles+1)>>1;
493  }
494 
495  void reset()
496  {
497  myCycles = 1;
498  }
499 
500 private:
501  uint myCycles;
502 };
503 
504 namespace UT
505 {
506 namespace detail
507 {
509 {
510 public:
511  ThreadInit();
512  ~ThreadInit();
513 
514  ThreadInit(const ThreadInit &) = delete;
515  ThreadInit &operator=(const ThreadInit &) = delete;
516 
517 };
518 } // namespace detail
519 } // namespace UT
520 
521 class UT_StdThread : public std::thread
522 {
523 public:
524  UT_StdThread() = default;
525  template <typename Func, typename... Args>
526  UT_StdThread(Func &&func, Args &&... args)
527  : std::thread(
528  WrapFunctor<Func, Args...>(std::forward<Func>(func)),
529  std::forward<Args>(args)...)
530  {
531  }
532 
533  UT_StdThread(const UT_StdThread&) = delete;
534  UT_StdThread& operator=(const UT_StdThread&) = delete;
535  UT_StdThread(UT_StdThread&&) = default;
536  UT_StdThread& operator=(UT_StdThread&&) = default;
537 
538 private:
539  template <typename Func, typename... Args>
540  class WrapFunctor
541  {
542  public:
543  WrapFunctor(Func&& func)
544  : myFunc(std::move(func))
545  {
546  }
547 
548  decltype(auto) operator()(Args&&... args) const
549  {
551  return myFunc(std::forward<Args>(args)...);
552  }
553  private:
554  Func myFunc;
555  };
556 };
557 
559 {
560 public:
562 
563  explicit UT_StdThreadGroup(int nthreads = -1)
564  {
565  if (nthreads < 1)
566  nthreads = UT_Thread::getNumProcessors();
567 
568  myThreads.setSize(nthreads);
569  }
570 
571  UT_StdThreadGroup(const UT_StdThreadGroup&) = delete;
573 
574  thread_t& get(int idx)
575  {
576  return myThreads(idx);
577  }
578  const thread_t& get(int idx) const
579  {
580  return myThreads(idx);
581  }
583  {
584  return myThreads[idx];
585  }
586  const thread_t& operator[](int idx) const
587  {
588  return myThreads[idx];
589  }
590  bool joinable() const
591  {
592  for (auto&& t : myThreads)
593  {
594  if (!t.joinable())
595  return false;
596  }
597  return true;
598  }
599  bool joinable(int idx) const
600  {
601  return get(idx).joinable();
602  }
603  void join()
604  {
605  for (auto&& t : myThreads)
606  {
607  if (t.joinable())
608  t.join();
609  }
610  }
611 private:
612  UT_Array<thread_t> myThreads;
613 };
614 
615 // This function has been deprecated. Use SYSgetSTID instead.
616 static inline int SYS_DEPRECATED(12.5)
617 UTgetSTID()
618 {
620 }
621 
622 #endif
volatile State myState
Definition: UT_Thread.h:307
int getNumThreads() const
Definition: UT_Thread.h:388
void setUserData(void *user_data)
Definition: UT_Thread.h:378
#define SYS_DEPRECATED(__V__)
int64 getMemoryUsage(bool inclusive) const override
NOTE: This level doesn't own any data apart from itself.
Definition: UT_Thread.h:347
UT_StdThread()=default
The subsystem to initialize and cleanup UT.
Definition: UT_SubSystem.h:110
virtual int restartThread()=0
int myThreadCount
Definition: UT_Thread.h:397
void *(* UTthreadFunc)(void *)
Definition: UT_Thread.h:53
UTthreadFunc myCallback
Definition: UT_Thread.h:309
UT_StdThread(Func &&func, Args &&...args)
Definition: UT_Thread.h:526
UT_Thread * operator[](int index)
Definition: UT_Thread.h:446
SpinMode mySpinMode
Definition: UT_Thread.h:308
void * myCBData
Definition: UT_Thread.h:310
#define UT_API
Definition: UT_API.h:14
bool joinable(int idx) const
Definition: UT_Thread.h:599
UT_StdThread & operator=(const UT_StdThread &)=delete
UT_Thread * operator[](int which)
Definition: UT_Thread.h:390
int getEntries() const
Definition: UT_Thread.h:445
bool joinable() const
Definition: UT_Thread.h:590
UT_Thread ** myThreads
Definition: UT_Thread.h:398
thread_t & operator[](int idx)
Definition: UT_Thread.h:582
virtual void setState(State state)=0
UT_StdThreadGroup & operator=(const UT_StdThreadGroup &)=delete
#define UT_ASSERT_P(ZZ)
Definition: UT_Assert.h:155
int myThreadCount
Definition: UT_Thread.h:455
static int getNumProcessors()
virtual void waitForState(State desired)=0
void setFunc(UTthreadFunc func)
Definition: UT_Thread.h:369
virtual bool startThread(UTthreadFunc func, void *data, int stacksize)=0
UT_Thread & operator=(const UT_Thread &)=delete
long long int64
Definition: SYS_Types.h:116
virtual void killThread()=0
int64 myUserDataInc
Definition: UT_Thread.h:401
const UT_TaskScope * myTaskScope
Definition: UT_Thread.h:312
const thread_t & operator[](int idx) const
Definition: UT_Thread.h:586
FS_API bool cleanup(UT_StringArray &removed, UT_StringArray &error_files, exint &memory_freed, bool dry_run, const char *override_path=nullptr)
GLdouble t
Definition: glad.h:2397
virtual int suspendThread()=0
*tasks wait()
**Note that the tasks the is the thread number *for the or if it s being executed by a non pool thread(this *can happen in cases where the whole pool is occupied and the calling *thread contributes to running the work load).**Thread pool.Have fun
static int isMainThread()
Definition: UT_Thread.h:116
GLenum func
Definition: glcorearb.h:783
LeafData & operator=(const LeafData &)=delete
UTthreadFunc myFunc
Definition: UT_Thread.h:399
GLuint index
Definition: glcorearb.h:786
void yield() noexcept
Definition: thread.h:94
UT_Thread ** myThreads
Definition: UT_Thread.h:456
static void pause(uint cycles)
Definition: UT_Thread.h:155
**If you just want to fire and args
Definition: thread.h:618
int isActive()
Definition: UT_Thread.h:283
static void yield(bool higher_only=false)
virtual int waitThread(int block=1)=0
void * myUserData
Definition: UT_Thread.h:400
unsigned int uint
Definition: SYS_Types.h:45
state
Definition: core.h:2289
void setUserData(void *user_data_array, size_t structlen)
Definition: UT_Thread.h:373
Definition: format.h:1821
UT_StdThreadGroup(int nthreads=-1)
Definition: UT_Thread.h:563