thread.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/thread.h
  3. // Purpose: Thread API
  4. // Author: Guilhem Lavaux
  5. // Modified by: Vadim Zeitlin (modifications partly inspired by omnithreads
  6. // package from Olivetti & Oracle Research Laboratory)
  7. // Created: 04/13/98
  8. // Copyright: (c) Guilhem Lavaux
  9. // Licence: wxWindows licence
  10. /////////////////////////////////////////////////////////////////////////////
  11. #ifndef _WX_THREAD_H_
  12. #define _WX_THREAD_H_
  13. // ----------------------------------------------------------------------------
  14. // headers
  15. // ----------------------------------------------------------------------------
  16. // get the value of wxUSE_THREADS configuration flag
  17. #include "wx/defs.h"
  18. #if wxUSE_THREADS
  19. // ----------------------------------------------------------------------------
  20. // constants
  21. // ----------------------------------------------------------------------------
  22. enum wxMutexError
  23. {
  24. wxMUTEX_NO_ERROR = 0, // operation completed successfully
  25. wxMUTEX_INVALID, // mutex hasn't been initialized
  26. wxMUTEX_DEAD_LOCK, // mutex is already locked by the calling thread
  27. wxMUTEX_BUSY, // mutex is already locked by another thread
  28. wxMUTEX_UNLOCKED, // attempt to unlock a mutex which is not locked
  29. wxMUTEX_TIMEOUT, // LockTimeout() has timed out
  30. wxMUTEX_MISC_ERROR // any other error
  31. };
  32. enum wxCondError
  33. {
  34. wxCOND_NO_ERROR = 0,
  35. wxCOND_INVALID,
  36. wxCOND_TIMEOUT, // WaitTimeout() has timed out
  37. wxCOND_MISC_ERROR
  38. };
  39. enum wxSemaError
  40. {
  41. wxSEMA_NO_ERROR = 0,
  42. wxSEMA_INVALID, // semaphore hasn't been initialized successfully
  43. wxSEMA_BUSY, // returned by TryWait() if Wait() would block
  44. wxSEMA_TIMEOUT, // returned by WaitTimeout()
  45. wxSEMA_OVERFLOW, // Post() would increase counter past the max
  46. wxSEMA_MISC_ERROR
  47. };
  48. enum wxThreadError
  49. {
  50. wxTHREAD_NO_ERROR = 0, // No error
  51. wxTHREAD_NO_RESOURCE, // No resource left to create a new thread
  52. wxTHREAD_RUNNING, // The thread is already running
  53. wxTHREAD_NOT_RUNNING, // The thread isn't running
  54. wxTHREAD_KILLED, // Thread we waited for had to be killed
  55. wxTHREAD_MISC_ERROR // Some other error
  56. };
  57. enum wxThreadKind
  58. {
  59. wxTHREAD_DETACHED,
  60. wxTHREAD_JOINABLE
  61. };
  62. enum wxThreadWait
  63. {
  64. wxTHREAD_WAIT_BLOCK,
  65. wxTHREAD_WAIT_YIELD, // process events while waiting; MSW only
  66. // For compatibility reasons we use wxTHREAD_WAIT_YIELD by default as this
  67. // was the default behaviour of wxMSW 2.8 but it should be avoided as it's
  68. // dangerous and not portable.
  69. #if WXWIN_COMPATIBILITY_2_8
  70. wxTHREAD_WAIT_DEFAULT = wxTHREAD_WAIT_YIELD
  71. #else
  72. wxTHREAD_WAIT_DEFAULT = wxTHREAD_WAIT_BLOCK
  73. #endif
  74. };
  75. // Obsolete synonyms for wxPRIORITY_XXX for backwards compatibility-only
  76. enum
  77. {
  78. WXTHREAD_MIN_PRIORITY = wxPRIORITY_MIN,
  79. WXTHREAD_DEFAULT_PRIORITY = wxPRIORITY_DEFAULT,
  80. WXTHREAD_MAX_PRIORITY = wxPRIORITY_MAX
  81. };
  82. // There are 2 types of mutexes: normal mutexes and recursive ones. The attempt
  83. // to lock a normal mutex by a thread which already owns it results in
  84. // undefined behaviour (it always works under Windows, it will almost always
  85. // result in a deadlock under Unix). Locking a recursive mutex in such
  86. // situation always succeeds and it must be unlocked as many times as it has
  87. // been locked.
  88. //
  89. // However recursive mutexes have several important drawbacks: first, in the
  90. // POSIX implementation, they're less efficient. Second, and more importantly,
  91. // they CAN NOT BE USED WITH CONDITION VARIABLES under Unix! Using them with
  92. // wxCondition will work under Windows and some Unices (notably Linux) but will
  93. // deadlock under other Unix versions (e.g. Solaris). As it might be difficult
  94. // to ensure that a recursive mutex is not used with wxCondition, it is a good
  95. // idea to avoid using recursive mutexes at all. Also, the last problem with
  96. // them is that some (older) Unix versions don't support this at all -- which
  97. // results in a configure warning when building and a deadlock when using them.
  98. enum wxMutexType
  99. {
  100. // normal mutex: try to always use this one
  101. wxMUTEX_DEFAULT,
  102. // recursive mutex: don't use these ones with wxCondition
  103. wxMUTEX_RECURSIVE
  104. };
  105. // forward declarations
  106. class WXDLLIMPEXP_FWD_BASE wxThreadHelper;
  107. class WXDLLIMPEXP_FWD_BASE wxConditionInternal;
  108. class WXDLLIMPEXP_FWD_BASE wxMutexInternal;
  109. class WXDLLIMPEXP_FWD_BASE wxSemaphoreInternal;
  110. class WXDLLIMPEXP_FWD_BASE wxThreadInternal;
  111. // ----------------------------------------------------------------------------
  112. // A mutex object is a synchronization object whose state is set to signaled
  113. // when it is not owned by any thread, and nonsignaled when it is owned. Its
  114. // name comes from its usefulness in coordinating mutually-exclusive access to
  115. // a shared resource. Only one thread at a time can own a mutex object.
  116. // ----------------------------------------------------------------------------
  117. // you should consider wxMutexLocker whenever possible instead of directly
  118. // working with wxMutex class - it is safer
  119. class WXDLLIMPEXP_BASE wxMutex
  120. {
  121. public:
  122. // constructor & destructor
  123. // ------------------------
  124. // create either default (always safe) or recursive mutex
  125. wxMutex(wxMutexType mutexType = wxMUTEX_DEFAULT);
  126. // destroys the mutex kernel object
  127. ~wxMutex();
  128. // test if the mutex has been created successfully
  129. bool IsOk() const;
  130. // mutex operations
  131. // ----------------
  132. // Lock the mutex, blocking on it until it is unlocked by the other thread.
  133. // The result of locking a mutex already locked by the current thread
  134. // depend on the mutex type.
  135. //
  136. // The caller must call Unlock() later if Lock() returned wxMUTEX_NO_ERROR.
  137. wxMutexError Lock();
  138. // Same as Lock() but return wxMUTEX_TIMEOUT if the mutex can't be locked
  139. // during the given number of milliseconds
  140. wxMutexError LockTimeout(unsigned long ms);
  141. // Try to lock the mutex: if it is currently locked, return immediately
  142. // with an error. Otherwise the caller must call Unlock().
  143. wxMutexError TryLock();
  144. // Unlock the mutex. It is an error to unlock an already unlocked mutex
  145. wxMutexError Unlock();
  146. protected:
  147. wxMutexInternal *m_internal;
  148. friend class wxConditionInternal;
  149. wxDECLARE_NO_COPY_CLASS(wxMutex);
  150. };
  151. // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
  152. // this ensures that mutex is always unlocked, even if the function returns or
  153. // throws an exception before it reaches the end
  154. class WXDLLIMPEXP_BASE wxMutexLocker
  155. {
  156. public:
  157. // lock the mutex in the ctor
  158. wxMutexLocker(wxMutex& mutex)
  159. : m_isOk(false), m_mutex(mutex)
  160. { m_isOk = ( m_mutex.Lock() == wxMUTEX_NO_ERROR ); }
  161. // returns true if mutex was successfully locked in ctor
  162. bool IsOk() const
  163. { return m_isOk; }
  164. // unlock the mutex in dtor
  165. ~wxMutexLocker()
  166. { if ( IsOk() ) m_mutex.Unlock(); }
  167. private:
  168. // no assignment operator nor copy ctor
  169. wxMutexLocker(const wxMutexLocker&);
  170. wxMutexLocker& operator=(const wxMutexLocker&);
  171. bool m_isOk;
  172. wxMutex& m_mutex;
  173. };
  174. // ----------------------------------------------------------------------------
  175. // Critical section: this is the same as mutex but is only visible to the
  176. // threads of the same process. For the platforms which don't have native
  177. // support for critical sections, they're implemented entirely in terms of
  178. // mutexes.
  179. //
  180. // NB: wxCriticalSection object does not allocate any memory in its ctor
  181. // which makes it possible to have static globals of this class
  182. // ----------------------------------------------------------------------------
  183. // in order to avoid any overhead under platforms where critical sections are
  184. // just mutexes make all wxCriticalSection class functions inline
  185. #if !defined(__WINDOWS__)
  186. #define wxCRITSECT_IS_MUTEX 1
  187. #define wxCRITSECT_INLINE WXEXPORT inline
  188. #else // MSW
  189. #define wxCRITSECT_IS_MUTEX 0
  190. #define wxCRITSECT_INLINE
  191. #endif // MSW/!MSW
  192. enum wxCriticalSectionType
  193. {
  194. // recursive critical section
  195. wxCRITSEC_DEFAULT,
  196. // non-recursive critical section
  197. wxCRITSEC_NON_RECURSIVE
  198. };
  199. // you should consider wxCriticalSectionLocker whenever possible instead of
  200. // directly working with wxCriticalSection class - it is safer
  201. class WXDLLIMPEXP_BASE wxCriticalSection
  202. {
  203. public:
  204. // ctor & dtor
  205. wxCRITSECT_INLINE wxCriticalSection( wxCriticalSectionType critSecType = wxCRITSEC_DEFAULT );
  206. wxCRITSECT_INLINE ~wxCriticalSection();
  207. // enter the section (the same as locking a mutex)
  208. wxCRITSECT_INLINE void Enter();
  209. // try to enter the section (the same as trying to lock a mutex)
  210. wxCRITSECT_INLINE bool TryEnter();
  211. // leave the critical section (same as unlocking a mutex)
  212. wxCRITSECT_INLINE void Leave();
  213. private:
  214. #if wxCRITSECT_IS_MUTEX
  215. wxMutex m_mutex;
  216. #elif defined(__WINDOWS__)
  217. // we can't allocate any memory in the ctor, so use placement new -
  218. // unfortunately, we have to hardcode the sizeof() here because we can't
  219. // include windows.h from this public header and we also have to use the
  220. // union to force the correct (i.e. maximal) alignment
  221. //
  222. // if CRITICAL_SECTION size changes in Windows, you'll get an assert from
  223. // thread.cpp and will need to increase the buffer size
  224. #ifdef __WIN64__
  225. typedef char wxCritSectBuffer[40];
  226. #else // __WIN32__
  227. typedef char wxCritSectBuffer[24];
  228. #endif
  229. union
  230. {
  231. unsigned long m_dummy1;
  232. void *m_dummy2;
  233. wxCritSectBuffer m_buffer;
  234. };
  235. #endif // Unix&OS2/Win32
  236. wxDECLARE_NO_COPY_CLASS(wxCriticalSection);
  237. };
  238. #if wxCRITSECT_IS_MUTEX
  239. // implement wxCriticalSection using mutexes
  240. inline wxCriticalSection::wxCriticalSection( wxCriticalSectionType critSecType )
  241. : m_mutex( critSecType == wxCRITSEC_DEFAULT ? wxMUTEX_RECURSIVE : wxMUTEX_DEFAULT ) { }
  242. inline wxCriticalSection::~wxCriticalSection() { }
  243. inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
  244. inline bool wxCriticalSection::TryEnter() { return m_mutex.TryLock() == wxMUTEX_NO_ERROR; }
  245. inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
  246. #endif // wxCRITSECT_IS_MUTEX
  247. #undef wxCRITSECT_INLINE
  248. #undef wxCRITSECT_IS_MUTEX
  249. // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
  250. // to mutexes
  251. class WXDLLIMPEXP_BASE wxCriticalSectionLocker
  252. {
  253. public:
  254. wxCriticalSectionLocker(wxCriticalSection& cs)
  255. : m_critsect(cs)
  256. {
  257. m_critsect.Enter();
  258. }
  259. ~wxCriticalSectionLocker()
  260. {
  261. m_critsect.Leave();
  262. }
  263. private:
  264. wxCriticalSection& m_critsect;
  265. wxDECLARE_NO_COPY_CLASS(wxCriticalSectionLocker);
  266. };
  267. // ----------------------------------------------------------------------------
  268. // wxCondition models a POSIX condition variable which allows one (or more)
  269. // thread(s) to wait until some condition is fulfilled
  270. // ----------------------------------------------------------------------------
  271. class WXDLLIMPEXP_BASE wxCondition
  272. {
  273. public:
  274. // Each wxCondition object is associated with a (single) wxMutex object.
  275. // The mutex object MUST be locked before calling Wait()
  276. wxCondition(wxMutex& mutex);
  277. // dtor is not virtual, don't use this class polymorphically
  278. ~wxCondition();
  279. // return true if the condition has been created successfully
  280. bool IsOk() const;
  281. // NB: the associated mutex MUST be locked beforehand by the calling thread
  282. //
  283. // it atomically releases the lock on the associated mutex
  284. // and starts waiting to be woken up by a Signal()/Broadcast()
  285. // once its signaled, then it will wait until it can reacquire
  286. // the lock on the associated mutex object, before returning.
  287. wxCondError Wait();
  288. // std::condition_variable-like variant that evaluates the associated condition
  289. template<typename Functor>
  290. wxCondError Wait(const Functor& predicate)
  291. {
  292. while ( !predicate() )
  293. {
  294. wxCondError e = Wait();
  295. if ( e != wxCOND_NO_ERROR )
  296. return e;
  297. }
  298. return wxCOND_NO_ERROR;
  299. }
  300. // exactly as Wait() except that it may also return if the specified
  301. // timeout elapses even if the condition hasn't been signalled: in this
  302. // case, the return value is wxCOND_TIMEOUT, otherwise (i.e. in case of a
  303. // normal return) it is wxCOND_NO_ERROR.
  304. //
  305. // the timeout parameter specifies an interval that needs to be waited for
  306. // in milliseconds
  307. wxCondError WaitTimeout(unsigned long milliseconds);
  308. // NB: the associated mutex may or may not be locked by the calling thread
  309. //
  310. // this method unblocks one thread if any are blocking on the condition.
  311. // if no thread is blocking in Wait(), then the signal is NOT remembered
  312. // The thread which was blocking on Wait() will then reacquire the lock
  313. // on the associated mutex object before returning
  314. wxCondError Signal();
  315. // NB: the associated mutex may or may not be locked by the calling thread
  316. //
  317. // this method unblocks all threads if any are blocking on the condition.
  318. // if no thread is blocking in Wait(), then the signal is NOT remembered
  319. // The threads which were blocking on Wait() will then reacquire the lock
  320. // on the associated mutex object before returning.
  321. wxCondError Broadcast();
  322. #if WXWIN_COMPATIBILITY_2_6
  323. // deprecated version, don't use
  324. wxDEPRECATED( bool Wait(unsigned long milliseconds) );
  325. #endif // WXWIN_COMPATIBILITY_2_6
  326. private:
  327. wxConditionInternal *m_internal;
  328. wxDECLARE_NO_COPY_CLASS(wxCondition);
  329. };
  330. #if WXWIN_COMPATIBILITY_2_6
  331. inline bool wxCondition::Wait(unsigned long milliseconds)
  332. { return WaitTimeout(milliseconds) == wxCOND_NO_ERROR; }
  333. #endif // WXWIN_COMPATIBILITY_2_6
  334. // ----------------------------------------------------------------------------
  335. // wxSemaphore: a counter limiting the number of threads concurrently accessing
  336. // a shared resource
  337. // ----------------------------------------------------------------------------
  338. class WXDLLIMPEXP_BASE wxSemaphore
  339. {
  340. public:
  341. // specifying a maxcount of 0 actually makes wxSemaphore behave as if there
  342. // is no upper limit, if maxcount is 1 the semaphore behaves as a mutex
  343. wxSemaphore( int initialcount = 0, int maxcount = 0 );
  344. // dtor is not virtual, don't use this class polymorphically
  345. ~wxSemaphore();
  346. // return true if the semaphore has been created successfully
  347. bool IsOk() const;
  348. // wait indefinitely, until the semaphore count goes beyond 0
  349. // and then decrement it and return (this method might have been called
  350. // Acquire())
  351. wxSemaError Wait();
  352. // same as Wait(), but does not block, returns wxSEMA_NO_ERROR if
  353. // successful and wxSEMA_BUSY if the count is currently zero
  354. wxSemaError TryWait();
  355. // same as Wait(), but as a timeout limit, returns wxSEMA_NO_ERROR if the
  356. // semaphore was acquired and wxSEMA_TIMEOUT if the timeout has elapsed
  357. wxSemaError WaitTimeout(unsigned long milliseconds);
  358. // increments the semaphore count and signals one of the waiting threads
  359. wxSemaError Post();
  360. private:
  361. wxSemaphoreInternal *m_internal;
  362. wxDECLARE_NO_COPY_CLASS(wxSemaphore);
  363. };
  364. // ----------------------------------------------------------------------------
  365. // wxThread: class encapsulating a thread of execution
  366. // ----------------------------------------------------------------------------
  367. // there are two different kinds of threads: joinable and detached (default)
  368. // ones. Only joinable threads can return a return code and only detached
  369. // threads auto-delete themselves - the user should delete the joinable
  370. // threads manually.
  371. // NB: in the function descriptions the words "this thread" mean the thread
  372. // created by the wxThread object while "main thread" is the thread created
  373. // during the process initialization (a.k.a. the GUI thread)
  374. // On VMS thread pointers are 64 bits (also needed for other systems???
  375. #ifdef __VMS
  376. typedef unsigned long long wxThreadIdType;
  377. #else
  378. typedef unsigned long wxThreadIdType;
  379. #endif
  380. class WXDLLIMPEXP_BASE wxThread
  381. {
  382. public:
  383. // the return type for the thread function
  384. typedef void *ExitCode;
  385. // static functions
  386. // Returns the wxThread object for the calling thread. NULL is returned
  387. // if the caller is the main thread (but it's recommended to use
  388. // IsMain() and only call This() for threads other than the main one
  389. // because NULL is also returned on error). If the thread wasn't
  390. // created with wxThread class, the returned value is undefined.
  391. static wxThread *This();
  392. // Returns true if current thread is the main thread.
  393. //
  394. // Notice that it also returns true if main thread id hadn't been
  395. // initialized yet on the assumption that it's too early in wx startup
  396. // process for any other threads to have been created in this case.
  397. static bool IsMain()
  398. {
  399. return !ms_idMainThread || GetCurrentId() == ms_idMainThread;
  400. }
  401. // Return the main thread id
  402. static wxThreadIdType GetMainId() { return ms_idMainThread; }
  403. // Release the rest of our time slice letting the other threads run
  404. static void Yield();
  405. // Sleep during the specified period of time in milliseconds
  406. //
  407. // This is the same as wxMilliSleep().
  408. static void Sleep(unsigned long milliseconds);
  409. // get the number of system CPUs - useful with SetConcurrency()
  410. // (the "best" value for it is usually number of CPUs + 1)
  411. //
  412. // Returns -1 if unknown, number of CPUs otherwise
  413. static int GetCPUCount();
  414. // Get the platform specific thread ID and return as a long. This
  415. // can be used to uniquely identify threads, even if they are not
  416. // wxThreads. This is used by wxPython.
  417. static wxThreadIdType GetCurrentId();
  418. // sets the concurrency level: this is, roughly, the number of threads
  419. // the system tries to schedule to run in parallel. 0 means the
  420. // default value (usually acceptable, but may not yield the best
  421. // performance for this process)
  422. //
  423. // Returns true on success, false otherwise (if not implemented, for
  424. // example)
  425. static bool SetConcurrency(size_t level);
  426. // constructor only creates the C++ thread object and doesn't create (or
  427. // start) the real thread
  428. wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
  429. // functions that change the thread state: all these can only be called
  430. // from _another_ thread (typically the thread that created this one, e.g.
  431. // the main thread), not from the thread itself
  432. // create a new thread and optionally set the stack size on
  433. // platforms that support that - call Run() to start it
  434. // (special cased for watcom which won't accept 0 default)
  435. wxThreadError Create(unsigned int stackSize = 0);
  436. // starts execution of the thread - from the moment Run() is called
  437. // the execution of wxThread::Entry() may start at any moment, caller
  438. // shouldn't suppose that it starts after (or before) Run() returns.
  439. wxThreadError Run();
  440. // stops the thread if it's running and deletes the wxThread object if
  441. // this is a detached thread freeing its memory - otherwise (for
  442. // joinable threads) you still need to delete wxThread object
  443. // yourself.
  444. //
  445. // this function only works if the thread calls TestDestroy()
  446. // periodically - the thread will only be deleted the next time it
  447. // does it!
  448. //
  449. // will fill the rc pointer with the thread exit code if it's !NULL
  450. wxThreadError Delete(ExitCode *rc = NULL,
  451. wxThreadWait waitMode = wxTHREAD_WAIT_DEFAULT);
  452. // waits for a joinable thread to finish and returns its exit code
  453. //
  454. // Returns (ExitCode)-1 on error (for example, if the thread is not
  455. // joinable)
  456. ExitCode Wait(wxThreadWait waitMode = wxTHREAD_WAIT_DEFAULT);
  457. // kills the thread without giving it any chance to clean up - should
  458. // not be used under normal circumstances, use Delete() instead.
  459. // It is a dangerous function that should only be used in the most
  460. // extreme cases!
  461. //
  462. // The wxThread object is deleted by Kill() if the thread is
  463. // detachable, but you still have to delete it manually for joinable
  464. // threads.
  465. wxThreadError Kill();
  466. // pause a running thread: as Delete(), this only works if the thread
  467. // calls TestDestroy() regularly
  468. wxThreadError Pause();
  469. // resume a paused thread
  470. wxThreadError Resume();
  471. // priority
  472. // Sets the priority to "prio" which must be in 0..100 range (see
  473. // also wxPRIORITY_XXX constants).
  474. //
  475. // NB: the priority can only be set before the thread is created
  476. void SetPriority(unsigned int prio);
  477. // Get the current priority.
  478. unsigned int GetPriority() const;
  479. // thread status inquiries
  480. // Returns true if the thread is alive: i.e. running or suspended
  481. bool IsAlive() const;
  482. // Returns true if the thread is running (not paused, not killed).
  483. bool IsRunning() const;
  484. // Returns true if the thread is suspended
  485. bool IsPaused() const;
  486. // is the thread of detached kind?
  487. bool IsDetached() const { return m_isDetached; }
  488. // Get the thread ID - a platform dependent number which uniquely
  489. // identifies a thread inside a process
  490. wxThreadIdType GetId() const;
  491. wxThreadKind GetKind() const
  492. { return m_isDetached ? wxTHREAD_DETACHED : wxTHREAD_JOINABLE; }
  493. // Returns true if the thread was asked to terminate: this function should
  494. // be called by the thread from time to time, otherwise the main thread
  495. // will be left forever in Delete()!
  496. virtual bool TestDestroy();
  497. // dtor is public, but the detached threads should never be deleted - use
  498. // Delete() instead (or leave the thread terminate by itself)
  499. virtual ~wxThread();
  500. protected:
  501. // exits from the current thread - can be called only from this thread
  502. void Exit(ExitCode exitcode = 0);
  503. // entry point for the thread - called by Run() and executes in the context
  504. // of this thread.
  505. virtual void *Entry() = 0;
  506. // use this to call the Entry() virtual method
  507. void *CallEntry();
  508. // Callbacks which may be overridden by the derived class to perform some
  509. // specific actions when the thread is deleted or killed. By default they
  510. // do nothing.
  511. // This one is called by Delete() before actually deleting the thread and
  512. // is executed in the context of the thread that called Delete().
  513. virtual void OnDelete() {}
  514. // This one is called by Kill() before killing the thread and is executed
  515. // in the context of the thread that called Kill().
  516. virtual void OnKill() {}
  517. private:
  518. // no copy ctor/assignment operator
  519. wxThread(const wxThread&);
  520. wxThread& operator=(const wxThread&);
  521. // called when the thread exits - in the context of this thread
  522. //
  523. // NB: this function will not be called if the thread is Kill()ed
  524. virtual void OnExit() { }
  525. friend class wxThreadInternal;
  526. friend class wxThreadModule;
  527. // the main thread identifier, should be set on startup
  528. static wxThreadIdType ms_idMainThread;
  529. // the (platform-dependent) thread class implementation
  530. wxThreadInternal *m_internal;
  531. // protects access to any methods of wxThreadInternal object
  532. wxCriticalSection m_critsect;
  533. // true if the thread is detached, false if it is joinable
  534. bool m_isDetached;
  535. };
  536. // wxThreadHelperThread class
  537. // --------------------------
  538. class WXDLLIMPEXP_BASE wxThreadHelperThread : public wxThread
  539. {
  540. public:
  541. // constructor only creates the C++ thread object and doesn't create (or
  542. // start) the real thread
  543. wxThreadHelperThread(wxThreadHelper& owner, wxThreadKind kind)
  544. : wxThread(kind), m_owner(owner)
  545. { }
  546. protected:
  547. // entry point for the thread -- calls Entry() in owner.
  548. virtual void *Entry();
  549. private:
  550. // the owner of the thread
  551. wxThreadHelper& m_owner;
  552. // no copy ctor/assignment operator
  553. wxThreadHelperThread(const wxThreadHelperThread&);
  554. wxThreadHelperThread& operator=(const wxThreadHelperThread&);
  555. };
  556. // ----------------------------------------------------------------------------
  557. // wxThreadHelper: this class implements the threading logic to run a
  558. // background task in another object (such as a window). It is a mix-in: just
  559. // derive from it to implement a threading background task in your class.
  560. // ----------------------------------------------------------------------------
  561. class WXDLLIMPEXP_BASE wxThreadHelper
  562. {
  563. private:
  564. void KillThread()
  565. {
  566. // If wxThreadHelperThread is detached and is about to finish, it will
  567. // set m_thread to NULL so don't delete it then.
  568. // But if KillThread is called before wxThreadHelperThread (in detached mode)
  569. // sets it to NULL, then the thread object still exists and can be killed
  570. wxCriticalSectionLocker locker(m_critSection);
  571. if ( m_thread )
  572. {
  573. m_thread->Kill();
  574. if ( m_kind == wxTHREAD_JOINABLE )
  575. delete m_thread;
  576. m_thread = NULL;
  577. }
  578. }
  579. public:
  580. // constructor only initializes m_thread to NULL
  581. wxThreadHelper(wxThreadKind kind = wxTHREAD_JOINABLE)
  582. : m_thread(NULL), m_kind(kind) { }
  583. // destructor deletes m_thread
  584. virtual ~wxThreadHelper() { KillThread(); }
  585. #if WXWIN_COMPATIBILITY_2_8
  586. wxDEPRECATED( wxThreadError Create(unsigned int stackSize = 0) );
  587. #endif
  588. // create a new thread (and optionally set the stack size on platforms that
  589. // support/need that), call Run() to start it
  590. wxThreadError CreateThread(wxThreadKind kind = wxTHREAD_JOINABLE,
  591. unsigned int stackSize = 0)
  592. {
  593. KillThread();
  594. m_kind = kind;
  595. m_thread = new wxThreadHelperThread(*this, m_kind);
  596. return m_thread->Create(stackSize);
  597. }
  598. // entry point for the thread - called by Run() and executes in the context
  599. // of this thread.
  600. virtual void *Entry() = 0;
  601. // returns a pointer to the thread which can be used to call Run()
  602. wxThread *GetThread() const
  603. {
  604. wxCriticalSectionLocker locker((wxCriticalSection&)m_critSection);
  605. wxThread* thread = m_thread;
  606. return thread;
  607. }
  608. protected:
  609. wxThread *m_thread;
  610. wxThreadKind m_kind;
  611. wxCriticalSection m_critSection; // To guard the m_thread variable
  612. friend class wxThreadHelperThread;
  613. };
  614. #if WXWIN_COMPATIBILITY_2_8
  615. inline wxThreadError wxThreadHelper::Create(unsigned int stackSize)
  616. { return CreateThread(m_kind, stackSize); }
  617. #endif
  618. // call Entry() in owner, put it down here to avoid circular declarations
  619. inline void *wxThreadHelperThread::Entry()
  620. {
  621. void * const result = m_owner.Entry();
  622. wxCriticalSectionLocker locker(m_owner.m_critSection);
  623. // Detached thread will be deleted after returning, so make sure
  624. // wxThreadHelper::GetThread will not return an invalid pointer.
  625. // And that wxThreadHelper::KillThread will not try to kill
  626. // an already deleted thread
  627. if ( m_owner.m_kind == wxTHREAD_DETACHED )
  628. m_owner.m_thread = NULL;
  629. return result;
  630. }
  631. // ----------------------------------------------------------------------------
  632. // Automatic initialization
  633. // ----------------------------------------------------------------------------
  634. // GUI mutex handling.
  635. void WXDLLIMPEXP_BASE wxMutexGuiEnter();
  636. void WXDLLIMPEXP_BASE wxMutexGuiLeave();
  637. // macros for entering/leaving critical sections which may be used without
  638. // having to take them inside "#if wxUSE_THREADS"
  639. #define wxENTER_CRIT_SECT(cs) (cs).Enter()
  640. #define wxLEAVE_CRIT_SECT(cs) (cs).Leave()
  641. #define wxCRIT_SECT_DECLARE(cs) static wxCriticalSection cs
  642. #define wxCRIT_SECT_DECLARE_MEMBER(cs) wxCriticalSection cs
  643. #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(cs)
  644. // function for checking if we're in the main thread which may be used whether
  645. // wxUSE_THREADS is 0 or 1
  646. inline bool wxIsMainThread() { return wxThread::IsMain(); }
  647. #else // !wxUSE_THREADS
  648. // no thread support
  649. inline void wxMutexGuiEnter() { }
  650. inline void wxMutexGuiLeave() { }
  651. // macros for entering/leaving critical sections which may be used without
  652. // having to take them inside "#if wxUSE_THREADS"
  653. // (the implementation uses dummy structs to force semicolon after the macro;
  654. // also notice that Watcom doesn't like declaring a struct as a member so we
  655. // need to actually define it in wxCRIT_SECT_DECLARE_MEMBER)
  656. #define wxENTER_CRIT_SECT(cs) do {} while (0)
  657. #define wxLEAVE_CRIT_SECT(cs) do {} while (0)
  658. #define wxCRIT_SECT_DECLARE(cs) struct wxDummyCS##cs
  659. #define wxCRIT_SECT_DECLARE_MEMBER(cs) struct wxDummyCSMember##cs { }
  660. #define wxCRIT_SECT_LOCKER(name, cs) struct wxDummyCSLocker##name
  661. // if there is only one thread, it is always the main one
  662. inline bool wxIsMainThread() { return true; }
  663. #endif // wxUSE_THREADS/!wxUSE_THREADS
  664. // mark part of code as being a critical section: this macro declares a
  665. // critical section with the given name and enters it immediately and leaves
  666. // it at the end of the current scope
  667. //
  668. // example:
  669. //
  670. // int Count()
  671. // {
  672. // static int s_counter = 0;
  673. //
  674. // wxCRITICAL_SECTION(counter);
  675. //
  676. // return ++s_counter;
  677. // }
  678. //
  679. // this function is MT-safe in presence of the threads but there is no
  680. // overhead when the library is compiled without threads
  681. #define wxCRITICAL_SECTION(name) \
  682. wxCRIT_SECT_DECLARE(s_cs##name); \
  683. wxCRIT_SECT_LOCKER(cs##name##Locker, s_cs##name)
  684. // automatically lock GUI mutex in ctor and unlock it in dtor
  685. class WXDLLIMPEXP_BASE wxMutexGuiLocker
  686. {
  687. public:
  688. wxMutexGuiLocker() { wxMutexGuiEnter(); }
  689. ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
  690. };
  691. // -----------------------------------------------------------------------------
  692. // implementation only until the end of file
  693. // -----------------------------------------------------------------------------
  694. #if wxUSE_THREADS
  695. #if defined(__WINDOWS__) || defined(__OS2__) || defined(__EMX__) || defined(__DARWIN__)
  696. // unlock GUI if there are threads waiting for and lock it back when
  697. // there are no more of them - should be called periodically by the main
  698. // thread
  699. extern void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter();
  700. // returns true if the main thread has GUI lock
  701. extern bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread();
  702. // wakes up the main thread if it's sleeping inside ::GetMessage()
  703. extern void WXDLLIMPEXP_BASE wxWakeUpMainThread();
  704. #ifndef __DARWIN__
  705. // return true if the main thread is waiting for some other to terminate:
  706. // wxApp then should block all "dangerous" messages
  707. extern bool WXDLLIMPEXP_BASE wxIsWaitingForThread();
  708. #endif
  709. #endif // MSW, OS/2
  710. #endif // wxUSE_THREADS
  711. #endif // _WX_THREAD_H_