jthread.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. extern jlib_decl void callThreadTerminationHooks();
  48. //An exception safe way of ensuring that the thread termination hooks are called.
  49. class jlib_decl QueryTerminationCleanup
  50. {
  51. public:
  52. inline ~QueryTerminationCleanup() { callThreadTerminationHooks(); }
  53. };
  54. class jlib_decl Thread : public CInterface, public IThread
  55. {
  56. private:
  57. ThreadId threadid;
  58. unsigned short stacksize; // in 4K blocks
  59. int prioritydelta;
  60. int nicelevel;
  61. bool alive;
  62. unsigned tidlog;
  63. #ifdef _WIN32
  64. HANDLE hThread;
  65. static unsigned WINAPI _threadmain(LPVOID v);
  66. #else
  67. static void *_threadmain(void *v);
  68. #endif
  69. virtual int begin();
  70. void init(const char *name);
  71. void handleException(IException *e);
  72. void adjustNiceLevel();
  73. protected:
  74. struct cThreadName: implements IThreadName
  75. {
  76. char *threadname;
  77. const char *get() { return threadname; }
  78. } cthreadname;
  79. IThreadName *ithreadname;
  80. public:
  81. #ifndef _WIN32
  82. Semaphore suspend;
  83. Semaphore starting;
  84. #endif
  85. Semaphore stopped;
  86. IMPLEMENT_IINTERFACE;
  87. Thread(const char *_name) { init(_name); }
  88. Thread() { init(NULL); }
  89. ~Thread();
  90. void adjustPriority(int delta);
  91. bool isCurrentThread() const;
  92. void setNice(int nicelevel);
  93. void setStackSize(size32_t size); // required stack size in bytes - called before start() (obviously)
  94. const char *getName() { const char *ret = ithreadname?ithreadname->get():NULL; return ret?ret:"unknown"; }
  95. bool isAlive() { return alive; }
  96. bool join(unsigned timeout=INFINITE);
  97. virtual void start();
  98. virtual void startRelease();
  99. StringBuffer &getInfo(StringBuffer &str) { str.appendf("%8" I64F "X %6" I64F "d %u: %s",(__int64)threadid,(__int64)threadid,tidlog,getName()); return str; }
  100. const char *getLogInfo(int &thandle,unsigned &tid) {
  101. #ifdef _WIN32
  102. thandle = (int)(memsize_t)hThread;
  103. #elif defined __FreeBSD__ || defined __APPLE__
  104. thandle = (int)(memsize_t)threadid;
  105. #else
  106. thandle = threadid;
  107. #endif
  108. tid = tidlog;
  109. return getName();
  110. }
  111. // run method not implemented - concrete derived classes must do so
  112. static void setDefaultStackSize(size32_t size); // NB under windows requires linker setting (/stack:)
  113. IThreadName *queryThreadName() { return ithreadname; }
  114. void setThreadName(IThreadName *name) { ithreadname = name; }
  115. };
  116. interface IThreaded
  117. {
  118. virtual void main() = 0;
  119. protected:
  120. virtual ~IThreaded() {}
  121. };
  122. // utility class, useful for containing a thread
  123. class CThreaded : public Thread
  124. {
  125. IThreaded *owner;
  126. public:
  127. inline CThreaded(const char *name, IThreaded *_owner) : Thread(name), owner(_owner) { }
  128. inline CThreaded(const char *name) : Thread(name) { owner = NULL; }
  129. inline void init(IThreaded *_owner) { owner = _owner; start(); }
  130. virtual int run() { owner->main(); return 1; }
  131. };
  132. // Similar to above, but the underlying thread always remains running. This can make repeated start + join's significantly quicker
  133. class jlib_decl CThreadedPersistent : public CInterface
  134. {
  135. class CAThread : public Thread
  136. {
  137. CThreadedPersistent &owner;
  138. public:
  139. CAThread(CThreadedPersistent &_owner, const char *name) : Thread(name), owner(_owner) { }
  140. virtual int run() { owner.main(); return 1; }
  141. } athread;
  142. Owned<IException> exception;
  143. IThreaded *owner;
  144. Semaphore sem, joinSem;
  145. atomic_t state;
  146. bool halt;
  147. enum ThreadStates { s_ready, s_running, s_joining };
  148. void main();
  149. public:
  150. CThreadedPersistent(const char *name, IThreaded *_owner);
  151. ~CThreadedPersistent();
  152. void start();
  153. bool join(unsigned timeout=INFINITE);
  154. };
  155. // Asynchronous 'for' utility class
  156. // see HRPCUTIL.CPP for example of usage
  157. class jlib_decl CAsyncFor
  158. {
  159. public:
  160. void For(unsigned num,unsigned maxatonce,bool abortFollowingException=false,bool shuffled=false);
  161. virtual void Do(unsigned idx=0)=0;
  162. };
  163. // ---------------------------------------------------------------------------
  164. // Thread Pools
  165. // ---------------------------------------------------------------------------
  166. interface IPooledThread: extends IInterface // base class for deriving pooled thread (alternative to Thread)
  167. {
  168. public:
  169. virtual void init(void *param)=0; // called before main started (from within start)
  170. virtual void main()=0; // where threads code goes (param is passed from start)
  171. virtual bool stop()=0; // called to cause main to return, returns false if request rejected
  172. virtual bool canReuse()=0; // return true if object can be re-used (after stopped), otherwise released
  173. };
  174. interface IThreadFactory: extends IInterface // factory for creating new pooled instances (called when pool empty)
  175. {
  176. virtual IPooledThread *createNew()=0;
  177. };
  178. typedef IIteratorOf<IPooledThread> IPooledThreadIterator;
  179. typedef unsigned PooledThreadHandle;
  180. interface IThreadPool : extends IInterface
  181. {
  182. virtual PooledThreadHandle start(void *param)=0; // starts a new thread reuses stopped pool entries
  183. virtual PooledThreadHandle start(void *param,const char *name)=0; // starts a new thread reuses stopped pool entries
  184. 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
  185. virtual bool stop(PooledThreadHandle handle)=0; // initiates stop on specified thread (may return false)
  186. virtual bool stopAll(bool tryall=false)=0; // initiates stop on all threads, if tryall continues even if one or more fails
  187. virtual bool join(PooledThreadHandle handle,unsigned timeout=INFINITE)=0;
  188. // waits for a single thread to terminate
  189. virtual bool joinAll(bool del=true,unsigned timeout=INFINITE)=0; // waits for all threads in thread pool to terminate
  190. // if del true frees all pooled threads
  191. virtual IPooledThreadIterator *running()=0; // return an iterator for all currently running threads
  192. virtual unsigned runningCount()=0; // number of currently running threads
  193. virtual PooledThreadHandle startNoBlock(void *param)=0; // starts a new thread if it can do so without blocking, else throws exception
  194. virtual PooledThreadHandle startNoBlock(void *param,const char *name)=0; // starts a new thread if it can do so without blocking, else throws exception
  195. virtual void setStartDelayTracing(unsigned secs) = 0; // set start delay tracing period
  196. };
  197. extern jlib_decl IThreadPool *createThreadPool(
  198. const char *poolname, // trace name of pool
  199. IThreadFactory *factory, // factory for creating new thread instances
  200. IExceptionHandler *exceptionHandler=NULL, // optional exception handler
  201. unsigned defaultmax=50, // maximum number of threads before starts blocking
  202. unsigned delay=1000, // maximum delay on each block
  203. unsigned stacksize=0, // stack size (bytes) 0 is default
  204. unsigned timeoutOnRelease=INFINITE, // maximum time waited for thread to terminate on releasing pool
  205. unsigned targetpoolsize=0 // target maximum size of pool (default same as defaultmax)
  206. );
  207. extern jlib_decl StringBuffer &getThreadList(StringBuffer &str);
  208. extern jlib_decl unsigned getThreadCount();
  209. extern jlib_decl StringBuffer &getThreadName(int thandle,unsigned logtid,StringBuffer &name); // either thandle or tid should be 0
  210. // Simple pipe process support
  211. interface ISimpleReadStream;
  212. #define START_FAILURE (199) // return code if program cannot be started
  213. interface IPipeProcess: extends IInterface
  214. {
  215. virtual bool run(const char *title,const char *prog, const char *dir,
  216. bool hasinput,bool hasoutput,bool haserror=false,
  217. size32_t stderrbufsize=0, // set to non-zero to automatically buffer stderror output
  218. bool newProcessGroup=false) = 0;
  219. virtual bool hasInput() = 0; // i.e. can write to pipe
  220. virtual size32_t write(size32_t sz, const void *buffer) = 0; // write pipe process standard output
  221. virtual bool hasOutput() = 0; // i.e. can read from pipe
  222. virtual size32_t read(size32_t sz, void *buffer) = 0; // read from pipe process standard output
  223. virtual ISimpleReadStream *getOutputStream() = 0; // read from pipe process standard output
  224. virtual bool hasError() = 0; // i.e. can read from pipe stderr
  225. virtual size32_t readError(size32_t sz, void *buffer) = 0; // read from pipe process standard error
  226. virtual ISimpleReadStream *getErrorStream() = 0; // read from pipe process standard error
  227. virtual unsigned wait() = 0; // returns return code
  228. virtual unsigned wait(unsigned timeoutms, bool &timedout) = 0; // sets timedout to true if times out
  229. virtual void closeInput() = 0; // indicate finished input to pipe
  230. virtual void closeOutput() = 0; // indicate finished reading from pipe (generally called automatically)
  231. virtual void closeError() = 0; // indicate finished reading from pipe stderr
  232. virtual void abort() = 0;
  233. virtual void notifyTerminated(HANDLE pid,unsigned retcode) = 0; // internal
  234. virtual HANDLE getProcessHandle() = 0; // used to auto kill
  235. virtual void setenv(const char *var, const char *value) = 0; // Set a value to be passed in the called process environment
  236. };
  237. extern jlib_decl IPipeProcess *createPipeProcess(const char *allowedprograms=NULL);
  238. //--------------------------------------------------------
  239. interface IWorkQueueItem: extends IInterface
  240. {
  241. virtual void execute()=0;
  242. };
  243. interface IWorkQueueThread: extends IInterface
  244. {
  245. virtual void post(IWorkQueueItem *item)=0; // takes ownership of item
  246. virtual void wait()=0;
  247. virtual unsigned pending()=0;
  248. };
  249. // Simple lightweight async worker queue
  250. // internally thread persists for specified time waiting before self destroying
  251. extern jlib_decl IWorkQueueThread *createWorkQueueThread(unsigned persisttime=1000*60);
  252. #endif