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 #include <functional>
36 
37 #if defined(WIN32)
38 # include <intrin.h>
39  typedef int ut_thread_id_t;
40 #elif defined(USE_PTHREADS)
41 # include <sched.h>
42 # include <pthread.h>
43  typedef pthread_t ut_thread_id_t;
44 #else
45  #error Unsupported Platform for UT_Thread
46 #endif
47 
48 #define UT_INVALID_THREAD_ID ((ut_thread_id_t)0)
49 
50 // some stack size defines
51 #define UT_THREAD_DEFAULT_STACK_SIZE (8U*1024U*1024U)
52 #define UT_THREAD_SMALL_STACK_SIZE (1U*1024U*1024U)
53 
54 typedef void *(*UTthreadFunc)(void*);
55 
56 // forward declarations
57 class UT_TaskScope;
58 
60 {
61 public:
62  // The destructor will wait until the thread is idle before it completes
63  // If you wish to kill the thread, call killThread() first.
64  virtual ~UT_Thread();
65 
66  // This enum specifies the current state for a persistent thread. The
67  // thread will typically be running or idle. If the thread is idle, it's
68  // behaviour will be determined by the SpinState.
69  enum State
70  {
72  ThreadRunning
73  };
74 
75  // // The thread status determines how the thread will behave once the
76  // callback function is completed:
77  // ThreadSingleRun - The thread cannot be restarted
78  // ThreadLowUsage - The thread will yield cycles while idle
79  //
80  enum SpinMode
81  {
84  };
85 
86  /// Allocate a new thread
87  /// @param spin_mode Use ThreadSingleRun to have it exit when the thread
88  /// callback is finished. Otherwise, ThreadLowUsage
89  /// will cause the thread to loop back and wait for
90  /// more startThread() calls to run different thread
91  /// callbacks in the same thread.
92  /// @param uses_tbb Leave at true unless you absolutely know that no
93  /// TBB tasks will be spawned in thread callbacks.
94  static UT_Thread *allocThread(SpinMode spin_mode, bool uses_tbb=true);
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  /// Returns true if configureMaxThreads() has been called at least once
212  static bool isMaxThreadsConfigured();
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 
221  {
222  public:
225  };
226 
227  /// Return function pointer to terminate task scheduler that is activated
228  /// by configureMaxThreads(). This function should called prior to exit()
229  /// in order to avoid possible deadlocks when the process exits. Note that
230  /// multiple calls to the termination function are handled by only
231  /// terminating the first time. After that, no task scheduling is allowed.
232  using TerminateFunc = void (*)();
233  static TerminateFunc getTaskSchedulerExitCallback();
234 
235  // Start the thread running. If the thread is not in idle state, the
236  // thread will wait until it's in idle before starting. If the thread
237  // doesn't exist yet, it will be created.
238  virtual bool startThread(UTthreadFunc func, void *data,
239  int stacksize) = 0;
240 
241  // Use the global thread stack size set by configureMaxThreads()
242  bool startThread(UTthreadFunc func, void *data);
243 
244  // This method is called when the thread function is first entered.
245  // By default it does nothing but some sub-classes may need this.
246  virtual void threadStarted();
247 
248  // This method is called when the thread function is returned from.
249  // By default it sets the state to idle.
250  virtual void threadEnded();
251 
252 
253  // Some thread architectures have very expensive resources (i.e. sproc()
254  // threads). While these threads spin (are idle), they consume system
255  // resources. This method will let the user know whether the threads are
256  // resource hogs (so that if they spin for a long time, they could
257  // possibley be cleaned up).
258  virtual int isResourceHog() const;
259 
260  // For persistent threads (which get restarted)
261  virtual State getState();
262  virtual SpinMode getSpinMode();
263  virtual void waitForState(State desired) = 0;
264  virtual void setSpinMode(SpinMode spin_mode);
265 
266  // Terminate the thread process
267  virtual void killThread() = 0;
268 
269  // If it's possible to perform these tasks, the return code will be 1. If
270  // not, the return code will be 0.
271  virtual int suspendThread() = 0;
272  virtual int restartThread() = 0;
273 
274  int isActive()
275  { return waitThread(0); }
276 
277  /// NOTE: This level doesn't own any data apart from itself.
278  virtual int64 getMemoryUsage(bool inclusive) const = 0;
279 
280 protected:
281  // System dependent internal functions.
282  // waitThread() returns 1 if the thread is still active (i.e. exists) and
283  // should return 0 if the thread doesn't exist. If waitThread detects
284  // that the thread no longer exists, it should do appropriate cleanup.
285  virtual int waitThread(int block=1) = 0;
286 
287  // Quick check to see that the thread is really active
288  virtual int isValid();
289 
290  // This method can be used to kill an idle process.
291  void killIdle();
292 
293  static void *threadWrapper(void *data);
294 
295  // Internally used to change the state safely.
296  virtual void setState(State state) = 0;
297 
298  volatile State myState;
301  void *myCBData;
302 
304  bool myUsesTBB;
305 
306  UT_Thread(SpinMode spin_mode, bool uses_tbb);
307 };
308 
309 // For debugging, the following uses a single thread (i.e. is not
310 // multi-threaded)
312 {
313 public:
314  UT_NullThread();
315  ~UT_NullThread() override;
316 
317  bool startThread(UTthreadFunc func, void *data,
318  int stacksize) override;
319  void killThread() override;
320  int waitThread(int block) override;
321  void waitForState(State) override;
322 
323  int suspendThread() override;
324  int restartThread() override;
325 
326  int64 getMemoryUsage(bool inclusive) const override
327  {
328  int64 mem = inclusive ? sizeof(*this) : 0;
329  // NOTE: We don't know how much memory Windows uses,
330  // so we can't count it.
331  return mem;
332  }
333 
334 protected:
335  void setState(State state) override;
336 };
337 
338 
340 {
341 public:
342  UT_ThreadSet(int nthreads=-1, int null_thread_if_1_cpu = 0);
343  ~UT_ThreadSet();
344 
346  {
347  myFunc = func;
348  }
349  void setUserData(void *user_data_array, size_t structlen)
350  {
351  myUserData = user_data_array;
352  myUserDataInc = structlen;
353  }
354  void setUserData(void *user_data)
355  {
356  myUserData = user_data;
357  myUserDataInc = 0;
358  }
359 
360  void reuse(UT_Thread::SpinMode spin_mode);
361  void go();
362  int wait(int block=1);
363 
364  int getNumThreads() const { return myThreadCount; }
365  UT_Thread *getThread(int which);
366  UT_Thread *operator[](int which)
367  {
368  UT_ASSERT_P(which < myThreadCount);
369  return myThreads[which];
370  }
371 
372 protected:
376  void *myUserData;
378 };
379 
381 {
382 public:
384  {
385  NON_BLOCKING = 0, // Only assign thread if one is available
386  BLOCKING = 1, // Block until a thread is free.
387  DYNAMIC = 2 // If no threads are availble, create a new one.
388  };
389 
390  // similar to UT_ThreadSet, but a bit simpler. Called UT_ThreadFarm
391  // because it farms out the next available thread. You also don't need to
392  // match the number of data chunks to the number of threads.
393  // ie.
394  // farm = new UT_ThreadFarm(4);
395  // while(!done) {
396  // thread = farm->nextThread();
397  // thread->startThread(entrypoint, mydata);
398  // }
399  // farm->wait();
400 
401  UT_ThreadFarm(int nthreads=-1);
402  ~UT_ThreadFarm();
403 
404  // waits for the next available thread, (or returns null if none are
405  // available and block = 0). thread_index will contain the thread index
406  // if you pass it a non-null pointer.
407  UT_Thread *nextThread(int *thread_index =0,
408  AssignmentStyle style = BLOCKING);
409 
410  // waits until all threads are finished (or, returns 0 if not finished and
411  // block = 0).
412  int wait(int block = 1);
413 
414  // deletes threads in the thread farm. if kill=1 the threads are killed before
415  // cleanup, otherwise wait(1) is called.
416  void cleanup(int kill = 0);
417 
418  int getEntries() const { return myThreadCount; }
420  {
421  UT_ASSERT_P(index < myThreadCount);
422  return myThreads[index];
423  }
424 
425 protected:
426  void addThreads(int thread_count);
427 
430 };
431 
432 // Gradual backoff when there's thread contention.
434 {
435 public:
436  UT_ThreadBackoff() : myCycles(1) {}
437 
438  static const uint cycles_for_noop = 4;
439  static const uint cycles_for_pause = cycles_for_noop * 4;
440  static const uint cycles_for_yield_higher = cycles_for_pause * 2;
441  static const uint cycles_for_yield_all = cycles_for_yield_higher * 2;
442 
443  // Same thresholds as hboost::detail::yield(), but different behaviour
444  void wait()
445  {
446  if (myCycles > cycles_for_yield_all)
447  {
448  // Yield the thread completely, to any and all comers.
449  UT_Thread::yield(false);
450  return;
451  }
452 
453  if (myCycles <= cycles_for_noop)
454  {
455  // Noop.
456  }
457  else if (myCycles <= cycles_for_pause)
458  {
459  UT_Thread::pause(myCycles);
460  }
461  else if (myCycles <= cycles_for_yield_higher)
462  {
463  UT_Thread::yield(true);
464  }
465  myCycles += (myCycles+1)>>1;
466  }
467 
468  void reset()
469  {
470  myCycles = 1;
471  }
472 
473 private:
474  uint myCycles;
475 };
476 
477 namespace UT
478 {
479 namespace detail
480 {
482 {
483 public:
484  ThreadInit(bool use_tbb);
485  ~ThreadInit();
486 
487  ThreadInit(const ThreadInit &) = delete;
488  ThreadInit &operator=(const ThreadInit &) = delete;
489 
490 private:
491  class InitTBB;
492  UT_UniquePtr<InitTBB> myInitTBB;
493 };
494 } // namespace detail
495 } // namespace UT
496 
497 template <bool UseTBB = true>
498 class UT_StdThread : public std::thread
499 {
500 public:
501  UT_StdThread() = default;
502  template <typename Func, typename... Args>
503  UT_StdThread(Func &&func, Args &&... args)
504  : std::thread(
505  WrapFunctor<Func, Args...>(std::forward<Func>(func)),
506  std::forward<Args>(args)...)
507  {
508  }
509 
510  UT_StdThread(const UT_StdThread&) = delete;
511  UT_StdThread& operator=(const UT_StdThread&) = delete;
512  UT_StdThread(UT_StdThread&&) = default;
513  UT_StdThread& operator=(UT_StdThread&&) = default;
514 
515 private:
516  template <typename Func, typename... Args>
517  class WrapFunctor
518  {
519  public:
520  WrapFunctor(Func&& func)
521  : myFunc(std::move(func))
522  {
523  }
524 
525  decltype(auto) operator()(Args&&... args) const
526  {
527  UT::detail::ThreadInit scope(UseTBB);
528  return myFunc(std::forward<Args>(args)...);
529  }
530  private:
531  Func myFunc;
532  };
533 };
534 
535 template <bool UseTBB = true>
537 {
538 public:
540 
541  explicit UT_StdThreadGroup(int nthreads = -1)
542  {
543  if (nthreads < 1)
544  nthreads = UT_Thread::getNumProcessors();
545 
546  myThreads.setSize(nthreads);
547  }
548 
549  UT_StdThreadGroup(const UT_StdThreadGroup&) = delete;
551 
552  thread_t& get(int idx)
553  {
554  return myThreads(idx);
555  }
556  const thread_t& get(int idx) const
557  {
558  return myThreads(idx);
559  }
561  {
562  return myThreads[idx];
563  }
564  const thread_t& operator[](int idx) const
565  {
566  return myThreads[idx];
567  }
568  bool joinable() const
569  {
570  for (auto&& t : myThreads)
571  {
572  if (!t.joinable())
573  return false;
574  }
575  return true;
576  }
577  bool joinable(int idx) const
578  {
579  return get(idx).joinable();
580  }
581  void join()
582  {
583  for (auto&& t : myThreads)
584  {
585  if (t.joinable())
586  t.join();
587  }
588  }
589 private:
590  UT_Array<thread_t> myThreads;
591 };
592 
593 // This function has been deprecated. Use SYSgetSTID instead.
594 static inline int SYS_DEPRECATED(12.5)
595 UTgetSTID()
596 {
598 }
599 
600 #endif
volatile State myState
Definition: UT_Thread.h:298
int getNumThreads() const
Definition: UT_Thread.h:364
void setUserData(void *user_data)
Definition: UT_Thread.h:354
#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:326
virtual int restartThread()=0
int myThreadCount
Definition: UT_Thread.h:373
void
Definition: png.h:1083
void *(* UTthreadFunc)(void *)
Definition: UT_Thread.h:54
UTthreadFunc myCallback
Definition: UT_Thread.h:300
UT_StdThreadGroup & operator=(const UT_StdThreadGroup &)=delete
UT_StdThread & operator=(const UT_StdThread &)=delete
UT_Thread * operator[](int index)
Definition: UT_Thread.h:419
SpinMode mySpinMode
Definition: UT_Thread.h:299
thread_t & operator[](int idx)
Definition: UT_Thread.h:560
UT_StdThread(Func &&func, Args &&...args)
Definition: UT_Thread.h:503
void * myCBData
Definition: UT_Thread.h:301
#define UT_API
Definition: UT_API.h:14
GLdouble GLdouble t
Definition: glew.h:1403
UT_Thread * operator[](int which)
Definition: UT_Thread.h:366
int getEntries() const
Definition: UT_Thread.h:418
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:33
UT_Thread ** myThreads
Definition: UT_Thread.h:374
virtual void setState(State state)=0
#define UT_ASSERT_P(ZZ)
Definition: UT_Assert.h:170
bool joinable() const
Definition: UT_Thread.h:568
int myThreadCount
Definition: UT_Thread.h:428
static int getNumProcessors()
virtual void waitForState(State desired)=0
void setFunc(UTthreadFunc func)
Definition: UT_Thread.h:345
virtual bool startThread(UTthreadFunc func, void *data, int stacksize)=0
long long int64
Definition: SYS_Types.h:116
virtual void killThread()=0
UT_StdThreadGroup(int nthreads=-1)
Definition: UT_Thread.h:541
int64 myUserDataInc
Definition: UT_Thread.h:377
const UT_TaskScope * myTaskScope
Definition: UT_Thread.h:303
bool myUsesTBB
Definition: UT_Thread.h:304
virtual int suspendThread()=0
GLboolean * data
Definition: glcorearb.h:130
*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:782
UTthreadFunc myFunc
Definition: UT_Thread.h:375
const thread_t & operator[](int idx) const
Definition: UT_Thread.h:564
GLuint index
Definition: glcorearb.h:785
void yield() noexcept
Definition: thread.h:93
UT_Thread ** myThreads
Definition: UT_Thread.h:429
static void pause(uint cycles)
Definition: UT_Thread.h:155
**If you just want to fire and args
Definition: thread.h:615
int isActive()
Definition: UT_Thread.h:274
static void yield(bool higher_only=false)
virtual int waitThread(int block=1)=0
void * myUserData
Definition: UT_Thread.h:376
bool joinable(int idx) const
Definition: UT_Thread.h:577
UT_StdThread()=default
unsigned int uint
Definition: SYS_Types.h:45
void setUserData(void *user_data_array, size_t structlen)
Definition: UT_Thread.h:349