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  /// @param uses_tbb Leave at true unless you absolutely know that no
95  /// TBB tasks will be spawned in thread callbacks.
96  static UT_Thread *allocThread(SpinMode spin_mode, bool uses_tbb=true);
97 
98  static int getNumProcessors();
99 
100  /// This is only valid in debug builds
101  static int activeThreadCount();
102 
103  /// Reset the number of threads that is used by Houdini. This will reread
104  /// the HOUDINI_MAXTHREADS setting.
105  /// @note There should be no active tasks when this is called.
106  /// @note Only call this from the MAIN THREAD!
107  static void resetNumProcessors();
108 
109  // getMyThreadId() is inlined for speed if we're using pthreads.
110 #if defined(USE_PTHREADS)
111  static ut_thread_id_t getMyThreadId() { return pthread_self(); }
112 #else
113  static ut_thread_id_t getMyThreadId();
114 #endif
115 
116  static ut_thread_id_t getMainThreadId();
117  static int getMainSequentialThreadId();
118  static inline int isMainThread()
119  {
120  return getMyThreadId() == getMainThreadId();
121  }
122 
123  /// Returns true if the current thread is a UT_Thread.
124  /// Returns false if the current thread is either the main thread
125  /// or a TBB thread.
126  static bool isUTThreadCurrent();
127 
128  /// Returns true iff the current thread is allowed to create more tasks.
129  /// This is sometimes disabled, to avoid needing to create a UT_TaskArena
130  /// for small cases that won't get much benefit from threading.
131  /// This should be checked by anything using tbb::parallel_for,
132  /// tbb::parallel_invoke, or anything else creating TBB tasks.
133  static bool isThreadingEnabled();
134 
135  /// This is used to disable (false) threading for the current thread,
136  /// to avoid needing to create a UT_TaskArena for small cases that won't
137  /// get much benefit from threading. It returns if it was enabled before.
138  /// It is also used to re-enable (true) threading for the current thread.
139  static bool setThreadingEnabled(bool will_be_enabled);
140 
142  {
143  public:
145  : myPreviouslyEnabled(setThreadingEnabled(false))
146  {}
148  {
149  if (myPreviouslyEnabled)
150  setThreadingEnabled(true);
151  }
152  private:
153  const bool myPreviouslyEnabled;
154  };
155 
156  // CPU pauses the task for a given number of cycles
157  static inline void pause(uint cycles)
158  {
159  for(uint i = 0; i < cycles; i++)
160 #if defined(USE_PTHREADS)
161 #if defined(ARM64)
162  __asm__ __volatile__("yield;");
163 #else
164  __asm__ __volatile__("pause;");
165 #endif
166 #else
167  _mm_pause();
168 #endif
169  }
170  // Yields the task to the scheduler.
171 #if defined(USE_PTHREADS)
172  static inline void yield(bool higher_only=false)
173  {
174  if (higher_only)
175  {
176  ::sched_yield();
177  }
178  else
179  {
180  // Sleep for 100ns. That's 10,000,000 sleep
181  // cycles a second (in case you don't have a
182  // calculator :-)
183  struct timespec ts = {0,100};
184  ::nanosleep(&ts, 0);
185  }
186  }
187 #else
188  static void yield(bool higher_only=false);
189 #endif
190 
191  /// This function has been deprecated. Use SYS_SequentialThreadIndex::get()
192  /// or SYSgetSTID instead.
193  static int SYS_DEPRECATED(12.5) getMySequentialThreadIndex()
194  { return SYS_SequentialThreadIndex::get(); }
195 
196  /// Configure the global number of tasks used by the system
197  /// - The default value of 0 uses the number of logical cores on the system
198  /// - A negative value wraps it from the number of logical cores.
199  /// eg. -1 will use all cores except for 1.
200  /// - If the negative value exceeds the number of logical cores, it is
201  /// clamped to a value of 1.
202  /// @note Only call this in the main thread when there are no tasks active.
203  /// @note This function is NOT thread-safe.
204  static void configureMaxThreads(int maxthreads = 0);
205 
206  /// Configure the default stack size for threads
207  /// - A value of 0 uses the stack size of the main thread
208  /// - A value larger than 0 will use that specific stack size
209  /// @note Only call this in the main thread when there are no tasks active.
210  /// @note This function is NOT thread-safe.
211  static void configureThreadStackSize(int stacksize);
212 
213  /// Returns true if configureMaxThreads() has been called at least once
214  static bool isMaxThreadsConfigured();
215 
216  /// Sets the current thread to minimum priority according to the rules
217  /// of the platform. This function fails if called on a thread that is
218  /// not a running UT_Thread.
219  /// Returns true if the operation was successful, otherwise returns false.
220  static bool minimizeThisThreadPriority();
221 
222 #if defined(MBSD)
223  /// Sets the quality of service (QoS) class of a thread. This is used by
224  /// the macOS scheduler to prioritize certain tasks.
225  /// @note Calling this is optional, however if it is called, it must be
226  /// called before startThread()
227  /// @note This method is only available on macOS
228  void setQoS(qos_class_t qos);
229 
230  /// Returns the quality of service (QoS) class of a thread.
231  /// @note This method is only available on macOS
232  /// @see setQoS()
233  qos_class_t getQoS() const;
234 #endif
235 
237  {
238  public:
241 
242  DisableGlobalControl(const DisableGlobalControl &) = delete;
244  };
245 
246  // Start the thread running. If the thread is not in idle state, the
247  // thread will wait until it's in idle before starting. If the thread
248  // doesn't exist yet, it will be created.
249  virtual bool startThread(UTthreadFunc func, void *data,
250  int stacksize) = 0;
251 
252  // Use the global thread stack size set by configureMaxThreads()
253  bool startThread(UTthreadFunc func, void *data);
254 
255  // This method is called when the thread function is first entered.
256  // By default it does nothing but some sub-classes may need this.
257  virtual void threadStarted();
258 
259  // This method is called when the thread function is returned from.
260  // By default it sets the state to idle.
261  virtual void threadEnded();
262 
263 
264  // Some thread architectures have very expensive resources (i.e. sproc()
265  // threads). While these threads spin (are idle), they consume system
266  // resources. This method will let the user know whether the threads are
267  // resource hogs (so that if they spin for a long time, they could
268  // possibley be cleaned up).
269  virtual int isResourceHog() const;
270 
271  // For persistent threads (which get restarted)
272  virtual State getState();
273  virtual SpinMode getSpinMode();
274  virtual void waitForState(State desired) = 0;
275  virtual void setSpinMode(SpinMode spin_mode);
276 
277  // Terminate the thread process
278  virtual void killThread() = 0;
279 
280  // If it's possible to perform these tasks, the return code will be 1. If
281  // not, the return code will be 0.
282  virtual int suspendThread() = 0;
283  virtual int restartThread() = 0;
284 
285  int isActive()
286  { return waitThread(0); }
287 
288  /// NOTE: This level doesn't own any data apart from itself.
289  virtual int64 getMemoryUsage(bool inclusive) const = 0;
290 
291 protected:
292  // System dependent internal functions.
293  // waitThread() returns 1 if the thread is still active (i.e. exists) and
294  // should return 0 if the thread doesn't exist. If waitThread detects
295  // that the thread no longer exists, it should do appropriate cleanup.
296  virtual int waitThread(int block=1) = 0;
297 
298  // Quick check to see that the thread is really active
299  virtual int isValid();
300 
301  // This method can be used to kill an idle process.
302  void killIdle();
303 
304  static void *threadWrapper(void *data);
305 
306  // Internally used to change the state safely.
307  virtual void setState(State state) = 0;
308 
309  volatile State myState;
312  void *myCBData;
313 
315  bool myUsesTBB;
316 
317 #if defined(MBSD)
318  // The quality of service (QoS) of this thread for the macOS scheduler
319  qos_class_t myQoS;
320 #endif
321 
322  UT_Thread(SpinMode spin_mode, bool uses_tbb);
323 
324 private:
325  friend class UT_SubSystem;
326 
327  static void onExit_();
328 };
329 
330 // For debugging, the following uses a single thread (i.e. is not
331 // multi-threaded)
333 {
334 public:
335  UT_NullThread();
336  ~UT_NullThread() override;
337 
338  UT_NullThread(const UT_NullThread &) = delete;
339  UT_NullThread &operator=(const UT_NullThread &) = delete;
340 
341  bool startThread(UTthreadFunc func, void *data,
342  int stacksize) override;
343  void killThread() override;
344  int waitThread(int block) override;
345  void waitForState(State) override;
346 
347  int suspendThread() override;
348  int restartThread() override;
349 
350  int64 getMemoryUsage(bool inclusive) const override
351  {
352  int64 mem = inclusive ? sizeof(*this) : 0;
353  // NOTE: We don't know how much memory Windows uses,
354  // so we can't count it.
355  return mem;
356  }
357 
358 protected:
359  void setState(State state) override;
360 };
361 
362 
364 {
365 public:
366  UT_ThreadSet(int nthreads=-1, int null_thread_if_1_cpu = 0);
367  ~UT_ThreadSet();
368 
369  UT_ThreadSet(const UT_ThreadSet &) = delete;
370  UT_ThreadSet &operator=(const UT_ThreadSet &) = delete;
371 
373  {
374  myFunc = func;
375  }
376  void setUserData(void *user_data_array, size_t structlen)
377  {
378  myUserData = user_data_array;
379  myUserDataInc = structlen;
380  }
381  void setUserData(void *user_data)
382  {
383  myUserData = user_data;
384  myUserDataInc = 0;
385  }
386 
387  void reuse(UT_Thread::SpinMode spin_mode);
388  void go();
389  int wait(int block=1);
390 
391  int getNumThreads() const { return myThreadCount; }
392  UT_Thread *getThread(int which);
393  UT_Thread *operator[](int which)
394  {
395  UT_ASSERT_P(which < myThreadCount);
396  return myThreads[which];
397  }
398 
399 protected:
403  void *myUserData;
405 };
406 
408 {
409 public:
411  {
412  NON_BLOCKING = 0, // Only assign thread if one is available
413  BLOCKING = 1, // Block until a thread is free.
414  DYNAMIC = 2 // If no threads are availble, create a new one.
415  };
416 
417  // similar to UT_ThreadSet, but a bit simpler. Called UT_ThreadFarm
418  // because it farms out the next available thread. You also don't need to
419  // match the number of data chunks to the number of threads.
420  // ie.
421  // farm = new UT_ThreadFarm(4);
422  // while(!done) {
423  // thread = farm->nextThread();
424  // thread->startThread(entrypoint, mydata);
425  // }
426  // farm->wait();
427 
428  UT_ThreadFarm(int nthreads=-1);
429  ~UT_ThreadFarm();
430 
431  UT_ThreadFarm(const UT_ThreadFarm &) = delete;
432  UT_ThreadFarm &operator=(const UT_ThreadFarm &) = delete;
433 
434  // waits for the next available thread, (or returns null if none are
435  // available and block = 0). thread_index will contain the thread index
436  // if you pass it a non-null pointer.
437  UT_Thread *nextThread(int *thread_index =0,
438  AssignmentStyle style = BLOCKING);
439 
440  // waits until all threads are finished (or, returns 0 if not finished and
441  // block = 0).
442  int wait(int block = 1);
443 
444  // deletes threads in the thread farm. if kill=1 the threads are killed before
445  // cleanup, otherwise wait(1) is called.
446  void cleanup(int kill = 0);
447 
448  int getEntries() const { return myThreadCount; }
450  {
451  UT_ASSERT_P(index < myThreadCount);
452  return myThreads[index];
453  }
454 
455 protected:
456  void addThreads(int thread_count);
457 
460 };
461 
462 // Gradual backoff when there's thread contention.
464 {
465 public:
466  UT_ThreadBackoff() : myCycles(1) {}
467 
468  static const uint cycles_for_noop = 4;
469  static const uint cycles_for_pause = cycles_for_noop * 4;
470  static const uint cycles_for_yield_higher = cycles_for_pause * 2;
471  static const uint cycles_for_yield_all = cycles_for_yield_higher * 2;
472 
473  // Same thresholds as hboost::detail::yield(), but different behaviour
474  void wait()
475  {
476  if (myCycles > cycles_for_yield_all)
477  {
478  // Yield the thread completely, to any and all comers.
479  UT_Thread::yield(false);
480  return;
481  }
482 
483  if (myCycles <= cycles_for_noop)
484  {
485  // Noop.
486  }
487  else if (myCycles <= cycles_for_pause)
488  {
489  UT_Thread::pause(myCycles);
490  }
491  else if (myCycles <= cycles_for_yield_higher)
492  {
493  UT_Thread::yield(true);
494  }
495  myCycles += (myCycles+1)>>1;
496  }
497 
498  void reset()
499  {
500  myCycles = 1;
501  }
502 
503 private:
504  uint myCycles;
505 };
506 
507 namespace UT
508 {
509 namespace detail
510 {
512 {
513 public:
514  ThreadInit(bool use_tbb);
515  ~ThreadInit();
516 
517  ThreadInit(const ThreadInit &) = delete;
518  ThreadInit &operator=(const ThreadInit &) = delete;
519 
520 private:
521  class InitTBB;
522  UT_UniquePtr<InitTBB> myInitTBB;
523 };
524 } // namespace detail
525 } // namespace UT
526 
527 template <bool UseTBB = true>
528 class UT_StdThread : public std::thread
529 {
530 public:
531  UT_StdThread() = default;
532  template <typename Func, typename... Args>
533  UT_StdThread(Func &&func, Args &&... args)
534  : std::thread(
535  WrapFunctor<Func, Args...>(std::forward<Func>(func)),
536  std::forward<Args>(args)...)
537  {
538  }
539 
540  UT_StdThread(const UT_StdThread&) = delete;
541  UT_StdThread& operator=(const UT_StdThread&) = delete;
542  UT_StdThread(UT_StdThread&&) = default;
543  UT_StdThread& operator=(UT_StdThread&&) = default;
544 
545 private:
546  template <typename Func, typename... Args>
547  class WrapFunctor
548  {
549  public:
550  WrapFunctor(Func&& func)
551  : myFunc(std::move(func))
552  {
553  }
554 
555  decltype(auto) operator()(Args&&... args) const
556  {
557  UT::detail::ThreadInit scope(UseTBB);
558  return myFunc(std::forward<Args>(args)...);
559  }
560  private:
561  Func myFunc;
562  };
563 };
564 
565 template <bool UseTBB = true>
567 {
568 public:
570 
571  explicit UT_StdThreadGroup(int nthreads = -1)
572  {
573  if (nthreads < 1)
574  nthreads = UT_Thread::getNumProcessors();
575 
576  myThreads.setSize(nthreads);
577  }
578 
579  UT_StdThreadGroup(const UT_StdThreadGroup&) = delete;
581 
582  thread_t& get(int idx)
583  {
584  return myThreads(idx);
585  }
586  const thread_t& get(int idx) const
587  {
588  return myThreads(idx);
589  }
591  {
592  return myThreads[idx];
593  }
594  const thread_t& operator[](int idx) const
595  {
596  return myThreads[idx];
597  }
598  bool joinable() const
599  {
600  for (auto&& t : myThreads)
601  {
602  if (!t.joinable())
603  return false;
604  }
605  return true;
606  }
607  bool joinable(int idx) const
608  {
609  return get(idx).joinable();
610  }
611  void join()
612  {
613  for (auto&& t : myThreads)
614  {
615  if (t.joinable())
616  t.join();
617  }
618  }
619 private:
620  UT_Array<thread_t> myThreads;
621 };
622 
623 // This function has been deprecated. Use SYSgetSTID instead.
624 static inline int SYS_DEPRECATED(12.5)
625 UTgetSTID()
626 {
628 }
629 
630 #endif
volatile State myState
Definition: UT_Thread.h:309
int getNumThreads() const
Definition: UT_Thread.h:391
void setUserData(void *user_data)
Definition: UT_Thread.h:381
#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:350
The subsystem to initialize and cleanup UT.
Definition: UT_SubSystem.h:109
virtual int restartThread()=0
int myThreadCount
Definition: UT_Thread.h:400
void *(* UTthreadFunc)(void *)
Definition: UT_Thread.h:53
UTthreadFunc myCallback
Definition: UT_Thread.h:311
UT_StdThreadGroup & operator=(const UT_StdThreadGroup &)=delete
UT_StdThread & operator=(const UT_StdThread &)=delete
UT_Thread * operator[](int index)
Definition: UT_Thread.h:449
SpinMode mySpinMode
Definition: UT_Thread.h:310
thread_t & operator[](int idx)
Definition: UT_Thread.h:590
UT_StdThread(Func &&func, Args &&...args)
Definition: UT_Thread.h:533
void * myCBData
Definition: UT_Thread.h:312
#define UT_API
Definition: UT_API.h:14
UT_Thread * operator[](int which)
Definition: UT_Thread.h:393
int getEntries() const
Definition: UT_Thread.h:448
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:39
UT_Thread ** myThreads
Definition: UT_Thread.h:401
virtual void setState(State state)=0
#define UT_ASSERT_P(ZZ)
Definition: UT_Assert.h:155
bool joinable() const
Definition: UT_Thread.h:598
int myThreadCount
Definition: UT_Thread.h:458
static int getNumProcessors()
virtual void waitForState(State desired)=0
void setFunc(UTthreadFunc func)
Definition: UT_Thread.h:372
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
UT_StdThreadGroup(int nthreads=-1)
Definition: UT_Thread.h:571
int64 myUserDataInc
Definition: UT_Thread.h:404
const UT_TaskScope * myTaskScope
Definition: UT_Thread.h:314
bool myUsesTBB
Definition: UT_Thread.h:315
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:118
GLenum func
Definition: glcorearb.h:783
LeafData & operator=(const LeafData &)=delete
UTthreadFunc myFunc
Definition: UT_Thread.h:402
const thread_t & operator[](int idx) const
Definition: UT_Thread.h:594
GLuint index
Definition: glcorearb.h:786
void yield() noexcept
Definition: thread.h:93
UT_Thread ** myThreads
Definition: UT_Thread.h:459
static void pause(uint cycles)
Definition: UT_Thread.h:157
**If you just want to fire and args
Definition: thread.h:609
int isActive()
Definition: UT_Thread.h:285
static void yield(bool higher_only=false)
virtual int waitThread(int block=1)=0
void * myUserData
Definition: UT_Thread.h:403
bool joinable(int idx) const
Definition: UT_Thread.h:607
UT_StdThread()=default
unsigned int uint
Definition: SYS_Types.h:45
void setUserData(void *user_data_array, size_t structlen)
Definition: UT_Thread.h:376
Definition: format.h:895