jthread.hpp 12 KB

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