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  /// Sets the current thread to minimum priority according to the rules
212  /// of the platform. This function fails if called on a thread that is
213  /// not a running UT_Thread.
214  /// Returns true if the operation was successful, otherwise returns false.
215  static bool minimizeThisThreadPriority();
216 
217 #if defined(MBSD)
218  /// Sets the quality of service (QoS) class of a thread. This is used by
219  /// the macOS scheduler to prioritize certain tasks.
220  /// @note Calling this is optional, however if it is called, it must be
221  /// called before startThread()
222  /// @note This method is only available on macOS
223  void setQoS(qos_class_t qos);
224 
225  /// Returns the quality of service (QoS) class of a thread.
226  /// @note This method is only available on macOS
227  /// @see setQoS()
228  qos_class_t getQoS() const;
229 #endif
230 
232  {
233  public:
236 
237  DisableGlobalControl(const DisableGlobalControl &) = delete;
239  };
240 
241  // Start the thread running. If the thread is not in idle state, the
242  // thread will wait until it's in idle before starting. If the thread
243  // doesn't exist yet, it will be created.
244  virtual bool startThread(UTthreadFunc func, void *data,
245  int stacksize) = 0;
246 
247  // Use the global thread stack size set by configureMaxThreads()
248  bool startThread(UTthreadFunc func, void *data);
249 
250  // This method is called when the thread function is first entered.
251  // By default it does nothing but some sub-classes may need this.
252  virtual void threadStarted();
253 
254  // This method is called when the thread function is returned from.
255  // By default it sets the state to idle.
256  virtual void threadEnded();
257 
258 
259  // Some thread architectures have very expensive resources (i.e. sproc()
260  // threads). While these threads spin (are idle), they consume system
261  // resources. This method will let the user know whether the threads are
262  // resource hogs (so that if they spin for a long time, they could
263  // possibley be cleaned up).
264  virtual int isResourceHog() const;
265 
266  // For persistent threads (which get restarted)
267  virtual State getState();
268  virtual SpinMode getSpinMode();
269  virtual void waitForState(State desired) = 0;
270  virtual void setSpinMode(SpinMode spin_mode);
271 
272  // Terminate the thread process
273  virtual void killThread() = 0;
274 
275  // If it's possible to perform these tasks, the return code will be 1. If
276  // not, the return code will be 0.
277  virtual int suspendThread() = 0;
278  virtual int restartThread() = 0;
279 
280  int isActive()
281  { return waitThread(0); }
282 
283  /// NOTE: This level doesn't own any data apart from itself.
284  virtual int64 getMemoryUsage(bool inclusive) const = 0;
285 
286 protected:
287  // System dependent internal functions.
288  // waitThread() returns 1 if the thread is still active (i.e. exists) and
289  // should return 0 if the thread doesn't exist. If waitThread detects
290  // that the thread no longer exists, it should do appropriate cleanup.
291  virtual int waitThread(int block=1) = 0;
292 
293  // Quick check to see that the thread is really active
294  virtual int isValid();
295 
296  // This method can be used to kill an idle process.
297  void killIdle();
298 
299  static void *threadWrapper(void *data);
300 
301  // Internally used to change the state safely.
302  virtual void setState(State state) = 0;
303 
304  volatile State myState;
307  void *myCBData;
308 
310 
311 #if defined(MBSD)
312  // The quality of service (QoS) of this thread for the macOS scheduler
313  qos_class_t myQoS;
314 #endif
315 
316  UT_Thread(SpinMode spin_mode);
317 
318 private:
319  friend class UT_SubSystem;
320 
321  static void onExit_();
322 };
323 
324 // For debugging, the following uses a single thread (i.e. is not
325 // multi-threaded)
327 {
328 public:
329  UT_NullThread();
330  ~UT_NullThread() override;
331 
332  UT_NullThread(const UT_NullThread &) = delete;
333  UT_NullThread &operator=(const UT_NullThread &) = delete;
334 
335  bool startThread(UTthreadFunc func, void *data,
336  int stacksize) override;
337  void killThread() override;
338  int waitThread(int block) override;
339  void waitForState(State) override;
340 
341  int suspendThread() override;
342  int restartThread() override;
343 
344  int64 getMemoryUsage(bool inclusive) const override
345  {
346  int64 mem = inclusive ? sizeof(*this) : 0;
347  // NOTE: We don't know how much memory Windows uses,
348  // so we can't count it.
349  return mem;
350  }
351 
352 protected:
353  void setState(State state) override;
354 };
355 
356 
358 {
359 public:
360  UT_ThreadSet(int nthreads=-1, int null_thread_if_1_cpu = 0);
361  ~UT_ThreadSet();
362 
363  UT_ThreadSet(const UT_ThreadSet &) = delete;
364  UT_ThreadSet &operator=(const UT_ThreadSet &) = delete;
365 
367  {
368  myFunc = func;
369  }
370  void setUserData(void *user_data_array, size_t structlen)
371  {
372  myUserData = user_data_array;
373  myUserDataInc = structlen;
374  }
375  void setUserData(void *user_data)
376  {
377  myUserData = user_data;
378  myUserDataInc = 0;
379  }
380 
381  void reuse(UT_Thread::SpinMode spin_mode);
382  void go();
383  int wait(int block=1);
384 
385  int getNumThreads() const { return myThreadCount; }
386  UT_Thread *getThread(int which);
387  UT_Thread *operator[](int which)
388  {
389  UT_ASSERT_P(which < myThreadCount);
390  return myThreads[which];
391  }
392 
393 protected:
397  void *myUserData;
399 };
400 
402 {
403 public:
405  {
406  NON_BLOCKING = 0, // Only assign thread if one is available
407  BLOCKING = 1, // Block until a thread is free.
408  DYNAMIC = 2 // If no threads are availble, create a new one.
409  };
410 
411  // similar to UT_ThreadSet, but a bit simpler. Called UT_ThreadFarm
412  // because it farms out the next available thread. You also don't need to
413  // match the number of data chunks to the number of threads.
414  // ie.
415  // farm = new UT_ThreadFarm(4);
416  // while(!done) {
417  // thread = farm->nextThread();
418  // thread->startThread(entrypoint, mydata);
419  // }
420  // farm->wait();
421 
422  UT_ThreadFarm(int nthreads=-1);
423  ~UT_ThreadFarm();
424 
425  UT_ThreadFarm(const UT_ThreadFarm &) = delete;
426  UT_ThreadFarm &operator=(const UT_ThreadFarm &) = delete;
427 
428  // waits for the next available thread, (or returns null if none are
429  // available and block = 0). thread_index will contain the thread index
430  // if you pass it a non-null pointer.
431  UT_Thread *nextThread(int *thread_index =0,
432  AssignmentStyle style = BLOCKING);
433 
434  // waits until all threads are finished (or, returns 0 if not finished and
435  // block = 0).
436  int wait(int block = 1);
437 
438  // deletes threads in the thread farm. if kill=1 the threads are killed before
439  // cleanup, otherwise wait(1) is called.
440  void cleanup(int kill = 0);
441 
442  int getEntries() const { return myThreadCount; }
444  {
445  UT_ASSERT_P(index < myThreadCount);
446  return myThreads[index];
447  }
448 
449 protected:
450  void addThreads(int thread_count);
451 
454 };
455 
456 // Gradual backoff when there's thread contention.
458 {
459 public:
460  UT_ThreadBackoff() : myCycles(1) {}
461 
462  static const uint cycles_for_noop = 4;
463  static const uint cycles_for_pause = cycles_for_noop * 4;
464  static const uint cycles_for_yield_higher = cycles_for_pause * 2;
465  static const uint cycles_for_yield_all = cycles_for_yield_higher * 2;
466 
467  // Same thresholds as hboost::detail::yield(), but different behaviour
468  void wait()
469  {
470  if (myCycles > cycles_for_yield_all)
471  {
472  // Yield the thread completely, to any and all comers.
473  UT_Thread::yield(false);
474  return;
475  }
476 
477  if (myCycles <= cycles_for_noop)
478  {
479  // Noop.
480  }
481  else if (myCycles <= cycles_for_pause)
482  {
483  UT_Thread::pause(myCycles);
484  }
485  else if (myCycles <= cycles_for_yield_higher)
486  {
487  UT_Thread::yield(true);
488  }
489  myCycles += (myCycles+1)>>1;
490  }
491 
492  void reset()
493  {
494  myCycles = 1;
495  }
496 
497 private:
498  uint myCycles;
499 };
500 
501 namespace UT
502 {
503 namespace detail
504 {
506 {
507 public:
508  ThreadInit();
509  ~ThreadInit();
510 
511  ThreadInit(const ThreadInit &) = delete;
512  ThreadInit &operator=(const ThreadInit &) = delete;
513 
514 };
515 } // namespace detail
516 } // namespace UT
517 
518 class UT_StdThread : public std::thread
519 {
520 public:
521  UT_StdThread() = default;
522  template <typename Func, typename... Args>
523  UT_StdThread(Func &&func, Args &&... args)
524  : std::thread(
525  WrapFunctor<Func, Args...>(std::forward<Func>(func)),
526  std::forward<Args>(args)...)
527  {
528  }
529 
530  UT_StdThread(const UT_StdThread&) = delete;
531  UT_StdThread& operator=(const UT_StdThread&) = delete;
532  UT_StdThread(UT_StdThread&&) = default;
533  UT_StdThread& operator=(UT_StdThread&&) = default;
534 
535 private:
536  template <typename Func, typename... Args>
537  class WrapFunctor
538  {
539  public:
540  WrapFunctor(Func&& func)
541  : myFunc(std::move(func))
542  {
543  }
544 
545  decltype(auto) operator()(Args&&... args) const
546  {
548  return myFunc(std::forward<Args>(args)...);
549  }
550  private:
551  Func myFunc;
552  };
553 };
554 
556 {
557 public:
559 
560  explicit UT_StdThreadGroup(int nthreads = -1)
561  {
562  if (nthreads < 1)
563  nthreads = UT_Thread::getNumProcessors();
564 
565  myThreads.setSize(nthreads);
566  }
567 
568  UT_StdThreadGroup(const UT_StdThreadGroup&) = delete;
570 
571  thread_t& get(int idx)
572  {
573  return myThreads(idx);
574  }
575  const thread_t& get(int idx) const
576  {
577  return myThreads(idx);
578  }
580  {
581  return myThreads[idx];
582  }
583  const thread_t& operator[](int idx) const
584  {
585  return myThreads[idx];
586  }
587  bool joinable() const
588  {
589  for (auto&& t : myThreads)
590  {
591  if (!t.joinable())
592  return false;
593  }
594  return true;
595  }
596  bool joinable(int idx) const
597  {
598  return get(idx).joinable();
599  }
600  void join()
601  {
602  for (auto&& t : myThreads)
603  {
604  if (t.joinable())
605  t.join();
606  }
607  }
608 private:
609  UT_Array<thread_t> myThreads;
610 };
611 
612 // This function has been deprecated. Use SYSgetSTID instead.
613 static inline int SYS_DEPRECATED(12.5)
614 UTgetSTID()
615 {
617 }
618 
619 #endif
volatile State myState
Definition: UT_Thread.h:304
int getNumThreads() const
Definition: UT_Thread.h:385
void setUserData(void *user_data)
Definition: UT_Thread.h:375
#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:344
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:394
void *(* UTthreadFunc)(void *)
Definition: UT_Thread.h:53
UTthreadFunc myCallback
Definition: UT_Thread.h:306
UT_StdThread(Func &&func, Args &&...args)
Definition: UT_Thread.h:523
UT_Thread * operator[](int index)
Definition: UT_Thread.h:443
SpinMode mySpinMode
Definition: UT_Thread.h:305
void * myCBData
Definition: UT_Thread.h:307
#define UT_API
Definition: UT_API.h:14
bool joinable(int idx) const
Definition: UT_Thread.h:596
UT_StdThread & operator=(const UT_StdThread &)=delete
UT_Thread * operator[](int which)
Definition: UT_Thread.h:387
int getEntries() const
Definition: UT_Thread.h:442
bool joinable() const
Definition: UT_Thread.h:587
UT_Thread ** myThreads
Definition: UT_Thread.h:395
thread_t & operator[](int idx)
Definition: UT_Thread.h:579
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:452
static int getNumProcessors()
virtual void waitForState(State desired)=0
void setFunc(UTthreadFunc func)
Definition: UT_Thread.h:366
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:398
const UT_TaskScope * myTaskScope
Definition: UT_Thread.h:309
const thread_t & operator[](int idx) const
Definition: UT_Thread.h:583
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:396
GLuint index
Definition: glcorearb.h:786
void yield() noexcept
Definition: thread.h:94
UT_Thread ** myThreads
Definition: UT_Thread.h:453
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:280
static void yield(bool higher_only=false)
virtual int waitThread(int block=1)=0
void * myUserData
Definition: UT_Thread.h:397
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:370
Definition: format.h:1821
UT_StdThreadGroup(int nthreads=-1)
Definition: UT_Thread.h:560