jthread.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #ifndef __JTHREAD__
  14. #define __JTHREAD__
  15. #include "jiface.hpp"
  16. #include "jmutex.hpp"
  17. #include "jexcept.hpp"
  18. #include "jhash.hpp"
  19. #ifdef _WIN32
  20. #define DEFAULT_THREAD_PRIORITY THREAD_PRIORITY_NORMAL
  21. #else
  22. // no thread priority handling?
  23. #endif
  24. interface jlib_decl IThread : public IInterface
  25. {
  26. virtual void start() = 0;
  27. virtual int run() = 0;
  28. };
  29. interface jlib_decl IThreadName
  30. {
  31. virtual const char *get()=0;
  32. };
  33. extern jlib_decl void addThreadExceptionHandler(IExceptionHandler *handler);
  34. extern jlib_decl void removeThreadExceptionHandler(IExceptionHandler *handler);
  35. extern jlib_decl void enableThreadSEH();
  36. extern jlib_decl void disableThreadSEH();
  37. extern jlib_decl unsigned threadLogID(); // for use in logging
  38. // A function registered via addThreadTermFunc will be called when the thread that registered that function
  39. // terminates. Such a function should call on to the previously registered function (if any) - generally you
  40. // would expect to store that value in thread-local storage.
  41. // This can be used to ensure that thread-specific objects can be properly destructed.
  42. // Note that threadpools also call the thread termination hook when each thread's main function terminates,
  43. // so the hook function should clear any variables if necessary rather than assuming that they will be cleared
  44. // at thread startup time.
  45. typedef void (*ThreadTermFunc)();
  46. extern jlib_decl ThreadTermFunc addThreadTermFunc(ThreadTermFunc onTerm);
  47. class jlib_decl Thread : public CInterface, public IThread
  48. {
  49. private:
  50. ThreadId threadid;
  51. unsigned short stacksize; // in 4K blocks
  52. char prioritydelta;
  53. char nicelevel;
  54. bool alive;
  55. unsigned tidlog;
  56. #ifdef _WIN32
  57. HANDLE hThread;
  58. static unsigned WINAPI _threadmain(LPVOID v);
  59. #else
  60. static void *_threadmain(void *v);
  61. #endif
  62. virtual int begin();
  63. void init(const char *name);
  64. void handleException(IException *e);
  65. void adjustNiceLevel();
  66. protected:
  67. struct cThreadName: implements IThreadName
  68. {
  69. char *threadname;
  70. const char *get() { return threadname; }
  71. } cthreadname;
  72. IThreadName *ithreadname;
  73. public:
  74. #ifndef _WIN32
  75. Semaphore suspend;
  76. Semaphore starting;
  77. #endif
  78. Semaphore stopped;
  79. IMPLEMENT_IINTERFACE;
  80. Thread(const char *_name) { init(_name); }
  81. Thread() { init(NULL); }
  82. ~Thread();
  83. void adjustPriority(char delta);
  84. void setNice(char nicelevel);
  85. void setStackSize(size32_t size); // required stack size in bytes - called before start() (obviously)
  86. const char *getName() { const char *ret = ithreadname?ithreadname->get():NULL; return ret?ret:"unknown"; }
  87. bool isAlive() { return alive; }
  88. bool join(unsigned timeout=INFINITE);
  89. virtual void start();
  90. virtual void startRelease();
  91. StringBuffer &getInfo(StringBuffer &str) { str.appendf("%8"I64F"X %6"I64F"d %u: %s",(__int64)threadid,(__int64)threadid,tidlog,getName()); return str; }
  92. const char *getLogInfo(int &thandle,unsigned &tid) {
  93. #ifdef _WIN32
  94. thandle = (int)(memsize_t)hThread;
  95. #elif defined __FreeBSD__ || defined __APPLE__
  96. thandle = (int)(memsize_t)threadid;
  97. #else
  98. thandle = threadid;
  99. #endif
  100. tid = tidlog;
  101. return getName();
  102. }
  103. // run method not implemented - concrete derived classes must do so
  104. static void setDefaultStackSize(size32_t size); // NB under windows requires linker setting (/stack:)
  105. IThreadName *queryThreadName() { return ithreadname; }
  106. void setThreadName(IThreadName *name) { ithreadname = name; }
  107. };
  108. interface IThreaded
  109. {
  110. virtual void main() = 0;
  111. };
  112. // utility class, useful for containing a thread
  113. class CThreaded : public Thread
  114. {
  115. IThreaded *owner;
  116. public:
  117. inline CThreaded(const char *name, IThreaded *_owner) : Thread(name), owner(_owner) { }
  118. inline CThreaded(const char *name) : Thread(name) { owner = NULL; }
  119. inline void init(IThreaded *_owner) { owner = _owner; start(); }
  120. virtual int run() { owner->main(); return 1; }
  121. };
  122. // Similar to above, but the underlying thread always remains running. This can make repeated start + join's significantly quicker
  123. class jlib_decl CThreadedPersistent : public CInterface
  124. {
  125. class CAThread : public Thread
  126. {
  127. CThreadedPersistent &owner;
  128. public:
  129. CAThread(CThreadedPersistent &_owner, const char *name) : Thread(name), owner(_owner) { }
  130. virtual int run() { owner.main(); return 1; }
  131. } athread;
  132. Owned<IException> exception;
  133. IThreaded *owner;
  134. Semaphore sem, joinSem;
  135. atomic_t state;
  136. bool halt;
  137. enum ThreadStates { s_ready, s_running, s_joining };
  138. void main();
  139. public:
  140. CThreadedPersistent(const char *name, IThreaded *_owner);
  141. ~CThreadedPersistent();
  142. void start();
  143. bool join(unsigned timeout=INFINITE);
  144. };
  145. // Asynchronous 'for' utility class
  146. // see HRPCUTIL.CPP for example of usage
  147. class jlib_decl CAsyncFor
  148. {
  149. public:
  150. void For(unsigned num,unsigned maxatonce,bool abortFollowingException=false,bool shuffled=false);
  151. virtual void Do(unsigned idx=0)=0;
  152. };
  153. // ---------------------------------------------------------------------------
  154. // Thread Pools
  155. // ---------------------------------------------------------------------------
  156. interface IPooledThread: extends IInterface // base class for deriving pooled thread (alternative to Thread)
  157. {
  158. public:
  159. virtual void init(void *param)=0; // called before main started (from within start)
  160. virtual void main()=0; // where threads code goes (param is passed from start)
  161. virtual bool stop()=0; // called to cause main to return, returns false if request rejected
  162. virtual bool canReuse()=0; // return true if object can be re-used (after stopped), otherwise released
  163. };
  164. interface IThreadFactory: extends IInterface // factory for creating new pooled instances (called when pool empty)
  165. {
  166. virtual IPooledThread *createNew()=0;
  167. };
  168. typedef IIteratorOf<IPooledThread> IPooledThreadIterator;
  169. typedef unsigned PooledThreadHandle;
  170. interface IThreadPool : extends IInterface
  171. {
  172. virtual PooledThreadHandle start(void *param)=0; // starts a new thread reuses stopped pool entries
  173. virtual PooledThreadHandle start(void *param,const char *name)=0; // starts a new thread reuses stopped pool entries
  174. virtual PooledThreadHandle start(void *param,const char *name,unsigned timeout)=0; // starts a new thread reuses stopped pool entries, throws exception if can't start within timeout
  175. virtual bool stop(PooledThreadHandle handle)=0; // initiates stop on specified thread (may return false)
  176. virtual bool stopAll(bool tryall=false)=0; // initiates stop on all threads, if tryall continues even if one or more fails
  177. virtual bool join(PooledThreadHandle handle,unsigned timeout=INFINITE)=0;
  178. // waits for a single thread to terminate
  179. virtual bool joinAll(bool del=true,unsigned timeout=INFINITE)=0; // waits for all threads in thread pool to terminate
  180. // if del true frees all pooled threads
  181. virtual IPooledThreadIterator *running()=0; // return an iterator for all currently running threads
  182. virtual unsigned runningCount()=0; // number of currently running threads
  183. virtual PooledThreadHandle startNoBlock(void *param)=0; // starts a new thread if it can do so without blocking, else throws exception
  184. virtual PooledThreadHandle startNoBlock(void *param,const char *name)=0; // starts a new thread if it can do so without blocking, else throws exception
  185. virtual void setStartDelayTracing(unsigned secs) = 0; // set start delay tracing period
  186. };
  187. extern jlib_decl IThreadPool *createThreadPool(
  188. const char *poolname, // trace name of pool
  189. IThreadFactory *factory, // factory for creating new thread instances
  190. IExceptionHandler *exceptionHandler=NULL, // optional exception handler
  191. unsigned defaultmax=50, // maximum number of threads before starts blocking
  192. unsigned delay=1000, // maximum delay on each block
  193. unsigned stacksize=0, // stack size (bytes) 0 is default
  194. unsigned timeoutOnRelease=INFINITE, // maximum time waited for thread to terminate on releasing pool
  195. unsigned targetpoolsize=0 // target maximum size of pool (default same as defaultmax)
  196. );
  197. extern jlib_decl StringBuffer &getThreadList(StringBuffer &str);
  198. extern jlib_decl unsigned getThreadCount();
  199. extern jlib_decl StringBuffer &getThreadName(int thandle,unsigned logtid,StringBuffer &name); // either thandle or tid should be 0
  200. // Simple pipe process support
  201. interface ISimpleReadStream;
  202. interface IPipeProcess: extends IInterface
  203. {
  204. virtual bool run(const char *title,const char *prog, const char *dir,
  205. bool hasinput,bool hasoutput,bool haserror=false,
  206. size32_t stderrbufsize=0) = 0; // set to non-zero to automatically buffer stderror output
  207. virtual bool hasInput() = 0; // i.e. can write to pipe
  208. virtual size32_t write(size32_t sz, const void *buffer) = 0; // write pipe process standard output
  209. virtual bool hasOutput() = 0; // i.e. can read from pipe
  210. virtual size32_t read(size32_t sz, void *buffer) = 0; // read from pipe process standard output
  211. virtual ISimpleReadStream *getOutputStream() = 0; // read from pipe process standard output
  212. virtual bool hasError() = 0; // i.e. can read from pipe stderr
  213. virtual size32_t readError(size32_t sz, void *buffer) = 0; // read from pipe process standard error
  214. virtual ISimpleReadStream *getErrorStream() = 0; // read from pipe process standard error
  215. virtual unsigned wait() = 0; // returns return code
  216. virtual unsigned wait(unsigned timeoutms, bool &timedout) = 0; // sets timedout to true if times out
  217. virtual void closeInput() = 0; // indicate finished input to pipe
  218. virtual void closeOutput() = 0; // indicate finished reading from pipe (generally called automatically)
  219. virtual void closeError() = 0; // indicate finished reading from pipe stderr
  220. virtual void abort() = 0;
  221. virtual void notifyTerminated(HANDLE pid,unsigned retcode) = 0; // internal
  222. virtual HANDLE getProcessHandle() = 0; // used to auto kill
  223. };
  224. extern jlib_decl IPipeProcess *createPipeProcess(const char *allowedprograms=NULL);
  225. //--------------------------------------------------------
  226. interface IWorkQueueItem: extends IInterface
  227. {
  228. virtual void execute()=0;
  229. };
  230. interface IWorkQueueThread: extends IInterface
  231. {
  232. virtual void post(IWorkQueueItem *item)=0; // takes ownership of item
  233. virtual void wait()=0;
  234. virtual unsigned pending()=0;
  235. };
  236. // Simple lightweight async worker queue
  237. // internally thread persists for specified time waiting before self destroying
  238. extern jlib_decl IWorkQueueThread *createWorkQueueThread(unsigned persisttime=1000*60);
  239. #endif