jthread.hpp 13 KB

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