HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros 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  * niceThread() - Prioritize thread (0 low priority, 100 high)
16  *
17  * TODO: It might be nice to have a way to get the exit status of a thread.
18  */
19 
20 #ifndef __UT_Thread__
21 #define __UT_Thread__
22 
23 #include "UT_API.h"
24 #include "UT_Assert.h"
25 #include "UT_Defines.h"
26 
27 #include <SYS/SYS_Deprecated.h>
29 #include <SYS/SYS_Types.h>
30 
31 #include <stdlib.h>
32 
33 #if defined(WIN32)
34 # include <intrin.h>
35  typedef int ut_thread_id_t;
36 #elif defined(USE_PTHREADS)
37 # include <sched.h>
38 # include <pthread.h>
39  typedef pthread_t ut_thread_id_t;
40 #else
41  #error Unsupported Platform for UT_Thread
42 #endif
43 
44 #define UT_INVALID_THREAD_ID ((ut_thread_id_t)0)
45 
46 // some stack size defines
47 #define UT_THREAD_DEFAULT_STACK_SIZE (8U*1024U*1024U)
48 #define UT_THREAD_SMALL_STACK_SIZE (1U*1024U*1024U)
49 
50 typedef void *(*UTthreadFunc)(void*);
51 
52 // forward declarations
53 class UT_TaskScope;
54 
56 {
57 public:
58  // The destructor will wait until the thread is idle before it completes
59  // If you wish to kill the thread, call killThread() first.
60  virtual ~UT_Thread();
61 
62  // This enum specifies the current state for a persistent thread. The
63  // thread will typically be running or idle. If the thread is idle, it's
64  // behaviour will be determined by the SpinState.
65  enum State
66  {
68  ThreadRunning
69  };
70 
71  // // The thread status determines how the thread will behave once the
72  // callback function is completed:
73  // ThreadSingleRun - The thread cannot be restarted
74  // ThreadLowUsage - The thread will yeild cycles while idle
75  //
76  enum SpinMode
77  {
80  };
81 
82  static UT_Thread *allocThread(SpinMode spin_mode);
83 
84  static int getNumProcessors();
85 
86  /// This is only valid in debug builds
87  static int activeThreadCount();
88 
89  /// Reset the number of threads that is used by Houdini. This will reread
90  /// the HOUDINI_MAXTHREADS setting.
91  /// @note There should be no active tasks when this is called.
92  /// @note Only call this from the MAIN THREAD!
93  static void resetNumProcessors();
94 
95  // getMyThreadId() is inlined for speed if we're using pthreads.
96 #if defined(USE_PTHREADS)
97  static ut_thread_id_t getMyThreadId() { return pthread_self(); }
98 #else
99  static ut_thread_id_t getMyThreadId();
100 #endif
101 
102  static ut_thread_id_t getMainThreadId();
103  static int getMainSequentialThreadId();
104  static inline int isMainThread()
105  {
106  return getMyThreadId() == getMainThreadId();
107  }
108 
109  // CPU pauses the task for a given number of cycles
110  static inline void pause(uint cycles)
111  {
112  for(uint i = 0; i < cycles; i++)
113 #if defined(USE_PTHREADS)
114  __asm__ __volatile__("pause;");
115 #else
116  _mm_pause();
117 #endif
118  }
119  // Yields the task to the scheduler.
120 #if defined(USE_PTHREADS)
121  static inline void yield(bool higher_only=false)
122  {
123  if (higher_only)
124  {
125  ::sched_yield();
126  }
127  else
128  {
129  // Sleep for 100ns. That's 10,000,000 sleep
130  // cycles a second (in case you don't have a
131  // calculator :-)
132  struct timespec ts = {0,100};
133  ::nanosleep(&ts, 0);
134  }
135  }
136 #else
137  static void yield(bool higher_only=false);
138 #endif
139 
140  /// This function has been deprecated. Use SYS_SequentialThreadIndex::get()
141  /// or SYSgetSTID instead.
142  static int SYS_DEPRECATED(12.5) getMySequentialThreadIndex()
143  { return SYS_SequentialThreadIndex::get(); }
144 
145  /// Configure the global number of tasks used by the system and the default
146  /// stack size for threads. For the @c stacksize:
147  /// - A value of -1 leaves the stack size unchanged
148  /// - A value of 0 uses the stack size of the main thread
149  /// - A value larger than 0 will use that specific stack size
150  /// @note Only call this in the main thread when there are no tasks active.
151  /// @note This function is NOT thread-safe.
152  static void configureMaxThreads(int maxthreads = -1,
153  int stacksize = -1);
154 
155  static bool isMaxThreadsConfigured();
156 
157  // Start the thread running. If the thread is not in idle state, the
158  // thread will wait until it's in idle before starting. If the thread
159  // doesn't exist yet, it will be created.
160  virtual bool startThread(UTthreadFunc func, void *data,
161  int stacksize) = 0;
162 
163  // Use the global thread stack size set by configureMaxThreads()
164  bool startThread(UTthreadFunc func, void *data);
165 
166  // This method is called when the thread function is first entered.
167  // By default it does nothing but some sub-classes may need this.
168  virtual void threadStarted();
169 
170  // This method is called when the thread function is returned from.
171  // By default it sets the state to idle.
172  virtual void threadEnded();
173 
174 
175  // Some thread architectures have very expensive resources (i.e. sproc()
176  // threads). While these threads spin (are idle), they consume system
177  // resources. This method will let the user know whether the threads are
178  // resource hogs (so that if they spin for a long time, they could
179  // possibley be cleaned up).
180  virtual int isResourceHog() const;
181 
182  // For persistent threads (which get restarted)
183  virtual State getState();
184  virtual SpinMode getSpinMode();
185  virtual void waitForState(State desired) = 0;
186  virtual void setSpinMode(SpinMode spin_mode);
187 
188  // Terminate the thread process
189  virtual void killThread() = 0;
190 
191  // If it's possible to perform these tasks, the return code will be 1. If
192  // not, the return code will be 0. Not all
193  virtual int niceThread(int priority) = 0;
194  virtual int suspendThread() = 0;
195  virtual int restartThread() = 0;
196 
197  int isActive()
198  { return waitThread(0); }
199 
200  static void interval(int count, int thisSection, int numSections,
201  int &start, int &len)
202  {
203  start = (int)(thisSection*count/(fpreal)numSections+0.5F);
204  len = (int)((thisSection+1)*count/(fpreal)numSections+0.5F) -
205  start;
206  }
207 
208  /// NOTE: This level doesn't own any data apart from itself.
209  virtual int64 getMemoryUsage(bool inclusive) const = 0;
210 
211 protected:
212  // System dependent internal functions.
213  // waitThread() returns 1 if the thread is still active (i.e. exists) and
214  // should return 0 if the thread doesn't exist. If waitThread detects
215  // that the thread no longer exists, it should do appropriate cleanup.
216  virtual int waitThread(int block=1) = 0;
217 
218  // Quick check to see that the thread is really active
219  virtual int isValid();
220 
221  // This method can be used to kill an idle process.
222  void killIdle();
223 
224  static void *threadWrapper(void *data);
225 
226  // Internally used to change the state safely.
227  virtual void setState(State state) = 0;
228 
229  volatile State myState;
232  void *myCBData;
233 
235 
236  UT_Thread(SpinMode spin_mode);
237 };
238 
239 // For debugging, the following uses a single thread (i.e. is not
240 // multi-threaded)
242 {
243 public:
244  UT_NullThread();
245  virtual ~UT_NullThread();
246 
247  virtual bool startThread(UTthreadFunc func, void *data,
248  int stacksize);
249  virtual void killThread();
250  virtual int waitThread(int block);
251  virtual void waitForState(State);
252 
253  virtual int niceThread(int priority);
254  virtual int suspendThread();
255  virtual int restartThread();
256 
257  virtual int64 getMemoryUsage(bool inclusive) const
258  {
259  int64 mem = inclusive ? sizeof(*this) : 0;
260  // NOTE: We don't know how much memory Windows uses,
261  // so we can't count it.
262  return mem;
263  }
264 
265 protected:
266  virtual void setState(State state);
267 };
268 
269 
271 {
272 public:
273  UT_ThreadSet(int nthreads=-1, int null_thread_if_1_cpu = 0);
274  ~UT_ThreadSet();
275 
277  {
278  myFunc = func;
279  }
280  void setUserData(void *user_data_array, size_t structlen)
281  {
282  myUserData = user_data_array;
283  myUserDataInc = structlen;
284  }
285  void setUserData(void *user_data)
286  {
287  myUserData = user_data;
288  myUserDataInc = 0;
289  }
290 
291  void reuse(UT_Thread::SpinMode spin_mode);
292  void go();
293  int wait(int block=1);
294 
295  int getNumThreads() const { return myThreadCount; }
296  UT_Thread *getThread(int which);
297  UT_Thread *operator[](int which)
298  {
299  UT_ASSERT_P(which < myThreadCount);
300  return myThreads[which];
301  }
302 
303 protected:
307  void *myUserData;
309 };
310 
312 {
313 public:
315  {
316  NON_BLOCKING = 0, // Only assign thread if one is available
317  BLOCKING = 1, // Block until a thread is free.
318  DYNAMIC = 2 // If no threads are availble, create a new one.
319  };
320 
321  // similar to UT_ThreadSet, but a bit simpler. Called UT_ThreadFarm
322  // because it farms out the next available thread. You also don't need to
323  // match the number of data chunks to the number of threads.
324  // ie.
325  // farm = new UT_ThreadFarm(4);
326  // while(!done) {
327  // thread = farm->nextThread();
328  // thread->startThread(entrypoint, mydata);
329  // }
330  // farm->wait();
331 
332  UT_ThreadFarm(int nthreads=-1);
333  ~UT_ThreadFarm();
334 
335  // waits for the next available thread, (or returns null if none are
336  // available and block = 0). thread_index will contain the thread index
337  // if you pass it a non-null pointer.
338  UT_Thread *nextThread(int *thread_index =0,
339  AssignmentStyle style = BLOCKING);
340 
341  // waits until all threads are finished (or, returns 0 if not finished and
342  // block = 0).
343  int wait(int block = 1);
344 
345  // deletes threads in the thread farm. if kill=1 the threads are killed before
346  // cleanup, otherwise wait(1) is called.
347  void cleanup(int kill = 0);
348 
349  int getEntries() const { return myThreadCount; }
351  {
352  UT_ASSERT_P(index < myThreadCount);
353  return myThreads[index];
354  }
355 
356 protected:
357  void addThreads(int thread_count);
358 
361 };
362 
363 // Gradual backoff when there's thread contention.
365 {
366 public:
367  UT_ThreadBackoff() : myCycles(1) {}
368 
369  static const uint cycles_for_noop = 4;
370  static const uint cycles_for_pause = cycles_for_noop * 4;
371  static const uint cycles_for_yield_higher = cycles_for_pause * 2;
372  static const uint cycles_for_yield_all = cycles_for_yield_higher * 2;
373 
374  // Same thresholds as hboost::detail::yield(), but different behaviour
375  void wait()
376  {
377  if (myCycles > cycles_for_yield_all)
378  {
379  // Yield the thread completely, to any and all comers.
380  UT_Thread::yield(false);
381  return;
382  }
383 
384  if (myCycles <= cycles_for_noop)
385  {
386  // Noop.
387  }
388  else if (myCycles <= cycles_for_pause)
389  {
390  UT_Thread::pause(myCycles);
391  }
392  else if (myCycles <= cycles_for_yield_higher)
393  {
394  UT_Thread::yield(true);
395  }
396  myCycles += (myCycles+1)>>1;
397  }
398 
399  void reset()
400  {
401  myCycles = 1;
402  }
403 
404 private:
405  uint myCycles;
406 };
407 
408 // This function has been deprecated. Use SYSgetSTID instead.
409 static inline int SYS_DEPRECATED(12.5)
410 UTgetSTID()
411 {
413 }
414 
415 #endif
volatile State myState
Definition: UT_Thread.h:229
int getNumThreads() const
Definition: UT_Thread.h:295
void setUserData(void *user_data)
Definition: UT_Thread.h:285
#define SYS_DEPRECATED(__V__)
virtual int restartThread()=0
int myThreadCount
Definition: UT_Thread.h:304
GLuint start
Definition: glcorearb.h:474
void *(* UTthreadFunc)(void *)
Definition: UT_Thread.h:50
UTthreadFunc myCallback
Definition: UT_Thread.h:231
UT_Thread * operator[](int index)
Definition: UT_Thread.h:350
SpinMode mySpinMode
Definition: UT_Thread.h:230
void * myCBData
Definition: UT_Thread.h:232
#define UT_API
Definition: UT_API.h:12
png_uint_32 i
Definition: png.h:2877
UT_Thread * operator[](int which)
Definition: UT_Thread.h:297
int getEntries() const
Definition: UT_Thread.h:349
#define UT_ASSERT_P(ZZ)
Definition: UT_Assert.h:101
UT_Thread ** myThreads
Definition: UT_Thread.h:305
virtual int64 getMemoryUsage(bool inclusive) const
NOTE: This level doesn't own any data apart from itself.
Definition: UT_Thread.h:257
long long int64
Definition: SYS_Types.h:100
virtual void setState(State state)=0
int myThreadCount
Definition: UT_Thread.h:359
virtual void waitForState(State desired)=0
void setFunc(UTthreadFunc func)
Definition: UT_Thread.h:276
virtual bool startThread(UTthreadFunc func, void *data, int stacksize)=0
virtual void killThread()=0
GLboolean * data
Definition: glcorearb.h:130
int64 myUserDataInc
Definition: UT_Thread.h:308
const UT_TaskScope * myTaskScope
Definition: UT_Thread.h:234
unsigned int uint
Definition: SYS_Types.h:33
GLint GLsizei count
Definition: glcorearb.h:404
virtual int suspendThread()=0
double fpreal
Definition: SYS_Types.h:263
virtual int niceThread(int priority)=0
static int isMainThread()
Definition: UT_Thread.h:104
GLenum func
Definition: glcorearb.h:782
static void interval(int count, int thisSection, int numSections, int &start, int &len)
Definition: UT_Thread.h:200
typedef int
Definition: png.h:1175
UTthreadFunc myFunc
Definition: UT_Thread.h:306
GLuint index
Definition: glcorearb.h:785
UT_Thread ** myThreads
Definition: UT_Thread.h:360
static void pause(uint cycles)
Definition: UT_Thread.h:110
int isActive()
Definition: UT_Thread.h:197
static void yield(bool higher_only=false)
virtual int waitThread(int block=1)=0
void * myUserData
Definition: UT_Thread.h:307
void setUserData(void *user_data_array, size_t structlen)
Definition: UT_Thread.h:280