thread.h 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: thread.h
  3. // Purpose: interface of all thread-related wxWidgets classes
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /** See wxCondition. */
  8. enum wxCondError
  9. {
  10. wxCOND_NO_ERROR = 0,
  11. wxCOND_INVALID,
  12. wxCOND_TIMEOUT, //!< WaitTimeout() has timed out
  13. wxCOND_MISC_ERROR
  14. };
  15. /**
  16. @class wxCondition
  17. wxCondition variables correspond to pthread conditions or to Win32 event objects.
  18. They may be used in a multithreaded application to wait until the given condition
  19. becomes @true which happens when the condition becomes signaled.
  20. For example, if a worker thread is doing some long task and another thread has
  21. to wait until it is finished, the latter thread will wait on the condition
  22. object and the worker thread will signal it on exit (this example is not
  23. perfect because in this particular case it would be much better to just
  24. wxThread::Wait for the worker thread, but if there are several worker threads
  25. it already makes much more sense).
  26. Note that a call to wxCondition::Signal may happen before the other thread calls
  27. wxCondition::Wait and, just as with the pthread conditions, the signal is then
  28. lost and so if you want to be sure that you don't miss it you must keep the
  29. mutex associated with the condition initially locked and lock it again before calling
  30. wxCondition::Signal. Of course, this means that this call is going to block
  31. until wxCondition::Wait is called by another thread.
  32. @section condition_example Example
  33. This example shows how a main thread may launch a worker thread which starts
  34. running and then waits until the main thread signals it to continue:
  35. @code
  36. class MySignallingThread : public wxThread
  37. {
  38. public:
  39. MySignallingThread(wxMutex *mutex, wxCondition *condition)
  40. {
  41. m_mutex = mutex;
  42. m_condition = condition;
  43. }
  44. virtual ExitCode Entry()
  45. {
  46. ... do our job ...
  47. // tell the other(s) thread(s) that we're about to terminate: we must
  48. // lock the mutex first or we might signal the condition before the
  49. // waiting threads start waiting on it!
  50. wxMutexLocker lock(*m_mutex);
  51. m_condition->Broadcast(); // same as Signal() here -- one waiter only
  52. return 0;
  53. }
  54. private:
  55. wxCondition *m_condition;
  56. wxMutex *m_mutex;
  57. };
  58. int main()
  59. {
  60. wxMutex mutex;
  61. wxCondition condition(mutex);
  62. // the mutex should be initially locked
  63. mutex.Lock();
  64. // create and run the thread but notice that it won't be able to
  65. // exit (and signal its exit) before we unlock the mutex below
  66. MySignallingThread *thread = new MySignallingThread(&mutex, &condition);
  67. thread->Run();
  68. // wait for the thread termination: Wait() atomically unlocks the mutex
  69. // which allows the thread to continue and starts waiting
  70. condition.Wait();
  71. // now we can exit
  72. return 0;
  73. }
  74. @endcode
  75. Of course, here it would be much better to simply use a joinable thread and
  76. call wxThread::Wait on it, but this example does illustrate the importance of
  77. properly locking the mutex when using wxCondition.
  78. @library{wxbase}
  79. @category{threading}
  80. @see wxThread, wxMutex
  81. */
  82. class wxCondition
  83. {
  84. public:
  85. /**
  86. Default and only constructor.
  87. The @a mutex must be locked by the caller before calling Wait() function.
  88. Use IsOk() to check if the object was successfully initialized.
  89. */
  90. wxCondition(wxMutex& mutex);
  91. /**
  92. Destroys the wxCondition object.
  93. The destructor is not virtual so this class should not be used polymorphically.
  94. */
  95. ~wxCondition();
  96. /**
  97. Broadcasts to all waiting threads, waking all of them up.
  98. Note that this method may be called whether the mutex associated with
  99. this condition is locked or not.
  100. @see Signal()
  101. */
  102. wxCondError Broadcast();
  103. /**
  104. Returns @true if the object had been initialized successfully, @false
  105. if an error occurred.
  106. */
  107. bool IsOk() const;
  108. /**
  109. Signals the object waking up at most one thread.
  110. If several threads are waiting on the same condition, the exact thread
  111. which is woken up is undefined. If no threads are waiting, the signal is
  112. lost and the condition would have to be signalled again to wake up any
  113. thread which may start waiting on it later.
  114. Note that this method may be called whether the mutex associated with this
  115. condition is locked or not.
  116. @see Broadcast()
  117. */
  118. wxCondError Signal();
  119. /**
  120. Waits until the condition is signalled.
  121. This method atomically releases the lock on the mutex associated with this
  122. condition (this is why it must be locked prior to calling Wait()) and puts the
  123. thread to sleep until Signal() or Broadcast() is called.
  124. It then locks the mutex again and returns.
  125. Note that even if Signal() had been called before Wait() without waking
  126. up any thread, the thread would still wait for another one and so it is
  127. important to ensure that the condition will be signalled after
  128. Wait() or the thread may sleep forever.
  129. @return Returns wxCOND_NO_ERROR on success, another value if an error occurred.
  130. @see WaitTimeout()
  131. */
  132. wxCondError Wait();
  133. /**
  134. Waits until the condition is signalled and the associated condition true.
  135. This is a convenience overload that may be used to ignore spurious
  136. awakenings while waiting for a specific condition to become true.
  137. Equivalent to
  138. @code
  139. while ( !predicate() )
  140. {
  141. wxCondError e = Wait();
  142. if ( e != wxCOND_NO_ERROR )
  143. return e;
  144. }
  145. return wxCOND_NO_ERROR;
  146. @endcode
  147. The predicate would typically be a C++11 lambda:
  148. @code
  149. condvar.Wait([]{return value == 1;});
  150. @endcode
  151. @since 3.0
  152. */
  153. template<typename Functor>
  154. wxCondError Wait(const Functor& predicate);
  155. /**
  156. Waits until the condition is signalled or the timeout has elapsed.
  157. This method is identical to Wait() except that it returns, with the
  158. return code of @c wxCOND_TIMEOUT as soon as the given timeout expires.
  159. @param milliseconds
  160. Timeout in milliseconds
  161. @return Returns wxCOND_NO_ERROR if the condition was signalled,
  162. wxCOND_TIMEOUT if the timeout elapsed before this happened or
  163. another error code from wxCondError enum.
  164. */
  165. wxCondError WaitTimeout(unsigned long milliseconds);
  166. };
  167. /**
  168. @class wxCriticalSectionLocker
  169. This is a small helper class to be used with wxCriticalSection objects.
  170. A wxCriticalSectionLocker enters the critical section in the constructor and
  171. leaves it in the destructor making it much more difficult to forget to leave
  172. a critical section (which, in general, will lead to serious and difficult
  173. to debug problems).
  174. Example of using it:
  175. @code
  176. void Set Foo()
  177. {
  178. // gs_critSect is some (global) critical section guarding access to the
  179. // object "foo"
  180. wxCriticalSectionLocker locker(gs_critSect);
  181. if ( ... )
  182. {
  183. // do something
  184. ...
  185. return;
  186. }
  187. // do something else
  188. ...
  189. return;
  190. }
  191. @endcode
  192. Without wxCriticalSectionLocker, you would need to remember to manually leave
  193. the critical section before each @c return.
  194. @library{wxbase}
  195. @category{threading}
  196. @see wxCriticalSection, wxMutexLocker
  197. */
  198. class wxCriticalSectionLocker
  199. {
  200. public:
  201. /**
  202. Constructs a wxCriticalSectionLocker object associated with given
  203. @a criticalsection and enters it.
  204. */
  205. wxCriticalSectionLocker(wxCriticalSection& criticalsection);
  206. /**
  207. Destructor leaves the critical section.
  208. */
  209. ~wxCriticalSectionLocker();
  210. };
  211. /**
  212. @class wxThreadHelper
  213. The wxThreadHelper class is a mix-in class that manages a single background
  214. thread, either detached or joinable (see wxThread for the differences).
  215. By deriving from wxThreadHelper, a class can implement the thread
  216. code in its own wxThreadHelper::Entry() method and easily share data and
  217. synchronization objects between the main thread and the worker thread.
  218. Doing this prevents the awkward passing of pointers that is needed when the
  219. original object in the main thread needs to synchronize with its worker thread
  220. in its own wxThread derived object.
  221. For example, wxFrame may need to make some calculations in a background thread
  222. and then display the results of those calculations in the main window.
  223. Ordinarily, a wxThread derived object would be created with the calculation
  224. code implemented in wxThread::Entry. To access the inputs to the calculation,
  225. the frame object would often need to pass a pointer to itself to the thread object.
  226. Similarly, the frame object would hold a pointer to the thread object.
  227. Shared data and synchronization objects could be stored in either object
  228. though the object without the data would have to access the data through
  229. a pointer.
  230. However with wxThreadHelper the frame object and the thread object are
  231. treated as the same object. Shared data and synchronization variables are
  232. stored in the single object, eliminating a layer of indirection and the
  233. associated pointers.
  234. Example:
  235. @code
  236. wxDECLARE_EVENT(myEVT_THREAD_UPDATE, wxThreadEvent);
  237. class MyFrame : public wxFrame, public wxThreadHelper
  238. {
  239. public:
  240. MyFrame(...) { ... }
  241. ~MyFrame()
  242. {
  243. // it's better to do any thread cleanup in the OnClose()
  244. // event handler, rather than in the destructor.
  245. // This is because the event loop for a top-level window is not
  246. // active anymore when its destructor is called and if the thread
  247. // sends events when ending, they won't be processed unless
  248. // you ended the thread from OnClose.
  249. // See @ref overview_windowdeletion for more info.
  250. }
  251. ...
  252. void DoStartALongTask();
  253. void OnThreadUpdate(wxThreadEvent& evt);
  254. void OnClose(wxCloseEvent& evt);
  255. ...
  256. protected:
  257. virtual wxThread::ExitCode Entry();
  258. // the output data of the Entry() routine:
  259. char m_data[1024];
  260. wxCriticalSection m_dataCS; // protects field above
  261. wxDECLARE_EVENT_TABLE();
  262. };
  263. wxDEFINE_EVENT(myEVT_THREAD_UPDATE, wxThreadEvent)
  264. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
  265. EVT_THREAD(wxID_ANY, myEVT_THREAD_UPDATE, MyFrame::OnThreadUpdate)
  266. EVT_CLOSE(MyFrame::OnClose)
  267. wxEND_EVENT_TABLE()
  268. void MyFrame::DoStartALongTask()
  269. {
  270. // we want to start a long task, but we don't want our GUI to block
  271. // while it's executed, so we use a thread to do it.
  272. if (CreateThread(wxTHREAD_JOINABLE) != wxTHREAD_NO_ERROR)
  273. {
  274. wxLogError("Could not create the worker thread!");
  275. return;
  276. }
  277. // go!
  278. if (GetThread()->Run() != wxTHREAD_NO_ERROR)
  279. {
  280. wxLogError("Could not run the worker thread!");
  281. return;
  282. }
  283. }
  284. wxThread::ExitCode MyFrame::Entry()
  285. {
  286. // IMPORTANT:
  287. // this function gets executed in the secondary thread context!
  288. int offset = 0;
  289. // here we do our long task, periodically calling TestDestroy():
  290. while (!GetThread()->TestDestroy())
  291. {
  292. // since this Entry() is implemented in MyFrame context we don't
  293. // need any pointer to access the m_data, m_processedData, m_dataCS
  294. // variables... very nice!
  295. // this is an example of the generic structure of a download thread:
  296. char buffer[1024];
  297. download_chunk(buffer, 1024); // this takes time...
  298. {
  299. // ensure no one reads m_data while we write it
  300. wxCriticalSectionLocker lock(m_dataCS);
  301. memcpy(m_data+offset, buffer, 1024);
  302. offset += 1024;
  303. }
  304. // VERY IMPORTANT: do not call any GUI function inside this
  305. // function; rather use wxQueueEvent():
  306. wxQueueEvent(this, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
  307. // we used pointer 'this' assuming it's safe; see OnClose()
  308. }
  309. // TestDestroy() returned true (which means the main thread asked us
  310. // to terminate as soon as possible) or we ended the long task...
  311. return (wxThread::ExitCode)0;
  312. }
  313. void MyFrame::OnClose(wxCloseEvent&)
  314. {
  315. // important: before terminating, we _must_ wait for our joinable
  316. // thread to end, if it's running; in fact it uses variables of this
  317. // instance and posts events to *this event handler
  318. if (GetThread() && // DoStartALongTask() may have not been called
  319. GetThread()->IsRunning())
  320. GetThread()->Wait();
  321. Destroy();
  322. }
  323. void MyFrame::OnThreadUpdate(wxThreadEvent& evt)
  324. {
  325. // ...do something... e.g. m_pGauge->Pulse();
  326. // read some parts of m_data just for fun:
  327. wxCriticalSectionLocker lock(m_dataCS);
  328. wxPrintf("%c", m_data[100]);
  329. }
  330. @endcode
  331. @library{wxbase}
  332. @category{threading}
  333. @see wxThread, wxThreadEvent
  334. */
  335. class wxThreadHelper
  336. {
  337. public:
  338. /**
  339. This constructor simply initializes internal member variables and tells
  340. wxThreadHelper which type the thread internally managed should be.
  341. */
  342. wxThreadHelper(wxThreadKind kind = wxTHREAD_JOINABLE);
  343. /**
  344. The destructor frees the resources associated with the thread, forcing
  345. it to terminate (it uses wxThread::Kill function).
  346. Because of the wxThread::Kill unsafety, you should always wait
  347. (with wxThread::Wait) for joinable threads to end or call wxThread::Delete
  348. on detached threads, instead of relying on this destructor for stopping
  349. the thread.
  350. */
  351. virtual ~wxThreadHelper();
  352. /**
  353. This is the entry point of the thread.
  354. This function is pure virtual and must be implemented by any derived class.
  355. The thread execution will start here.
  356. You'll typically want your Entry() to look like:
  357. @code
  358. wxThread::ExitCode Entry()
  359. {
  360. while (!GetThread()->TestDestroy())
  361. {
  362. // ... do some work ...
  363. if (IsWorkCompleted)
  364. break;
  365. if (HappenedStoppingError)
  366. return (wxThread::ExitCode)1; // failure
  367. }
  368. return (wxThread::ExitCode)0; // success
  369. }
  370. @endcode
  371. The returned value is the thread exit code which is only useful for
  372. joinable threads and is the value returned by @c "GetThread()->Wait()".
  373. This function is called by wxWidgets itself and should never be called
  374. directly.
  375. */
  376. virtual ExitCode Entry() = 0;
  377. /**
  378. Callback called by Delete() before actually deleting the thread.
  379. This function can be overridden by the derived class to perform some
  380. specific task when the thread is gracefully destroyed. Notice that it
  381. will be executed in the context of the thread that called Delete() and
  382. <b>not</b> in this thread's context.
  383. TestDestroy() will be true for the thread before OnDelete() gets
  384. executed.
  385. @since 2.9.2
  386. @see OnKill()
  387. */
  388. virtual void OnDelete();
  389. /**
  390. Callback called by Kill() before actually killing the thread.
  391. This function can be overridden by the derived class to perform some
  392. specific task when the thread is terminated. Notice that it will be
  393. executed in the context of the thread that called Kill() and <b>not</b>
  394. in this thread's context.
  395. @since 2.9.2
  396. @see OnDelete()
  397. */
  398. virtual void OnKill();
  399. /**
  400. @deprecated
  401. Use CreateThread() instead.
  402. */
  403. wxThreadError Create(unsigned int stackSize = 0);
  404. /**
  405. Creates a new thread of the given @a kind.
  406. The thread object is created in the suspended state, and you
  407. should call @ref wxThread::Run "GetThread()->Run()" to start running it.
  408. You may optionally specify the stack size to be allocated to it (ignored
  409. on platforms that don't support setting it explicitly, e.g. Unix).
  410. @return One of the ::wxThreadError enum values.
  411. */
  412. wxThreadError CreateThread(wxThreadKind kind = wxTHREAD_JOINABLE,
  413. unsigned int stackSize = 0);
  414. /**
  415. This is a public function that returns the wxThread object associated with
  416. the thread.
  417. */
  418. wxThread* GetThread() const;
  419. /**
  420. Returns the last type of thread given to the CreateThread() function
  421. or to the constructor.
  422. */
  423. wxThreadKind GetThreadKind() const;
  424. };
  425. /**
  426. Possible critical section types
  427. */
  428. enum wxCriticalSectionType
  429. {
  430. wxCRITSEC_DEFAULT,
  431. /** Recursive critical section under both Windows and Unix */
  432. wxCRITSEC_NON_RECURSIVE
  433. /** Non-recursive critical section under Unix, recursive under Windows */
  434. };
  435. /**
  436. @class wxCriticalSection
  437. A critical section object is used for exactly the same purpose as a wxMutex.
  438. The only difference is that under Windows platform critical sections are only
  439. visible inside one process, while mutexes may be shared among processes,
  440. so using critical sections is slightly more efficient.
  441. The terminology is also slightly different: mutex may be locked (or acquired)
  442. and unlocked (or released) while critical section is entered and left by the program.
  443. Finally, you should try to use wxCriticalSectionLocker class whenever
  444. possible instead of directly using wxCriticalSection for the same reasons
  445. wxMutexLocker is preferable to wxMutex - please see wxMutex for an example.
  446. @library{wxbase}
  447. @category{threading}
  448. @note Critical sections can be used before the wxWidgets library is fully
  449. initialized. In particular, it's safe to create global
  450. wxCriticalSection instances.
  451. @see wxThread, wxCondition, wxCriticalSectionLocker
  452. */
  453. class wxCriticalSection
  454. {
  455. public:
  456. /**
  457. Default constructor initializes critical section object.
  458. By default critical sections are recursive under Unix and Windows.
  459. */
  460. wxCriticalSection( wxCriticalSectionType critSecType = wxCRITSEC_DEFAULT );
  461. /**
  462. Destructor frees the resources.
  463. */
  464. ~wxCriticalSection();
  465. /**
  466. Enter the critical section (same as locking a mutex): if another thread
  467. has already entered it, this call will block until the other thread
  468. calls Leave().
  469. There is no error return for this function.
  470. After entering the critical section protecting a data variable,
  471. the thread running inside the critical section may safely use/modify it.
  472. Note that entering the same critical section twice or more from the same
  473. thread doesn't result in a deadlock; in this case in fact this function will
  474. immediately return.
  475. */
  476. void Enter();
  477. /**
  478. Try to enter the critical section (same as trying to lock a mutex).
  479. If it can't, immediately returns false.
  480. @since 2.9.3
  481. */
  482. bool TryEnter();
  483. /**
  484. Leave the critical section allowing other threads use the global data
  485. protected by it. There is no error return for this function.
  486. */
  487. void Leave();
  488. };
  489. /**
  490. The possible thread wait types.
  491. @since 2.9.2
  492. */
  493. enum wxThreadWait
  494. {
  495. /**
  496. No events are processed while waiting.
  497. This is the default under all platforms except for wxMSW.
  498. */
  499. wxTHREAD_WAIT_BLOCK,
  500. /**
  501. Yield for event dispatching while waiting.
  502. This flag is dangerous as it exposes the program using it to unexpected
  503. reentrancies in the same way as calling wxYield() function does so you
  504. are strongly advised to avoid its use and not wait for the thread
  505. termination from the main (GUI) thread at all to avoid making your
  506. application unresponsive.
  507. Also notice that this flag is not portable as it is only implemented in
  508. wxMSW and simply ignored under the other platforms.
  509. */
  510. wxTHREAD_WAIT_YIELD,
  511. /**
  512. Default wait mode for wxThread::Wait() and wxThread::Delete().
  513. For compatibility reasons, the default wait mode is currently
  514. wxTHREAD_WAIT_YIELD if WXWIN_COMPATIBILITY_2_8 is defined (and it is
  515. by default). However, as mentioned above, you're strongly encouraged to
  516. not use wxTHREAD_WAIT_YIELD and pass wxTHREAD_WAIT_BLOCK to wxThread
  517. method explicitly.
  518. */
  519. wxTHREAD_WAIT_DEFAULT = wxTHREAD_WAIT_YIELD
  520. };
  521. /**
  522. The possible thread kinds.
  523. */
  524. enum wxThreadKind
  525. {
  526. /** Detached thread */
  527. wxTHREAD_DETACHED,
  528. /** Joinable thread */
  529. wxTHREAD_JOINABLE
  530. };
  531. /**
  532. The possible thread errors.
  533. */
  534. enum wxThreadError
  535. {
  536. /** No error */
  537. wxTHREAD_NO_ERROR = 0,
  538. /** No resource left to create a new thread. */
  539. wxTHREAD_NO_RESOURCE,
  540. /** The thread is already running. */
  541. wxTHREAD_RUNNING,
  542. /** The thread isn't running. */
  543. wxTHREAD_NOT_RUNNING,
  544. /** Thread we waited for had to be killed. */
  545. wxTHREAD_KILLED,
  546. /** Some other error */
  547. wxTHREAD_MISC_ERROR
  548. };
  549. /**
  550. @class wxThread
  551. A thread is basically a path of execution through a program.
  552. Threads are sometimes called @e light-weight processes, but the fundamental difference
  553. between threads and processes is that memory spaces of different processes are
  554. separated while all threads share the same address space.
  555. While it makes it much easier to share common data between several threads, it
  556. also makes it much easier to shoot oneself in the foot, so careful use of
  557. synchronization objects such as mutexes (see wxMutex) or critical sections
  558. (see wxCriticalSection) is recommended.
  559. In addition, don't create global thread objects because they allocate memory
  560. in their constructor, which will cause problems for the memory checking system.
  561. @section thread_types Types of wxThreads
  562. There are two types of threads in wxWidgets: @e detached and @e joinable,
  563. modeled after the POSIX thread API. This is different from the Win32 API
  564. where all threads are joinable.
  565. By default wxThreads in wxWidgets use the @b detached behaviour.
  566. Detached threads delete themselves once they have completed, either by themselves
  567. when they complete processing or through a call to Delete(), and thus
  568. @b must be created on the heap (through the new operator, for example).
  569. Typically you'll want to store the instances of the detached wxThreads you
  570. allocate, so that you can call functions on them.
  571. Because of their nature however you'll need to always use a critical section
  572. when accessing them:
  573. @code
  574. // declare a new type of event, to be used by our MyThread class:
  575. wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent);
  576. wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent);
  577. class MyFrame;
  578. class MyThread : public wxThread
  579. {
  580. public:
  581. MyThread(MyFrame *handler)
  582. : wxThread(wxTHREAD_DETACHED)
  583. { m_pHandler = handler }
  584. ~MyThread();
  585. protected:
  586. virtual ExitCode Entry();
  587. MyFrame *m_pHandler;
  588. };
  589. class MyFrame : public wxFrame
  590. {
  591. public:
  592. ...
  593. ~MyFrame()
  594. {
  595. // it's better to do any thread cleanup in the OnClose()
  596. // event handler, rather than in the destructor.
  597. // This is because the event loop for a top-level window is not
  598. // active anymore when its destructor is called and if the thread
  599. // sends events when ending, they won't be processed unless
  600. // you ended the thread from OnClose.
  601. // See @ref overview_windowdeletion for more info.
  602. }
  603. ...
  604. void DoStartThread();
  605. void DoPauseThread();
  606. // a resume routine would be nearly identic to DoPauseThread()
  607. void DoResumeThread() { ... }
  608. void OnThreadUpdate(wxThreadEvent&);
  609. void OnThreadCompletion(wxThreadEvent&);
  610. void OnClose(wxCloseEvent&);
  611. protected:
  612. MyThread *m_pThread;
  613. wxCriticalSection m_pThreadCS; // protects the m_pThread pointer
  614. wxDECLARE_EVENT_TABLE();
  615. };
  616. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
  617. EVT_CLOSE(MyFrame::OnClose)
  618. EVT_MENU(Minimal_Start, MyFrame::DoStartThread)
  619. EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_UPDATE, MyFrame::OnThreadUpdate)
  620. EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_COMPLETED, MyFrame::OnThreadCompletion)
  621. wxEND_EVENT_TABLE()
  622. wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent)
  623. wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent)
  624. void MyFrame::DoStartThread()
  625. {
  626. m_pThread = new MyThread(this);
  627. if ( m_pThread->Run() != wxTHREAD_NO_ERROR )
  628. {
  629. wxLogError("Can't create the thread!");
  630. delete m_pThread;
  631. m_pThread = NULL;
  632. }
  633. // after the call to wxThread::Run(), the m_pThread pointer is "unsafe":
  634. // at any moment the thread may cease to exist (because it completes its work).
  635. // To avoid dangling pointers OnThreadExit() will set m_pThread
  636. // to NULL when the thread dies.
  637. }
  638. wxThread::ExitCode MyThread::Entry()
  639. {
  640. while (!TestDestroy())
  641. {
  642. // ... do a bit of work...
  643. wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
  644. }
  645. // signal the event handler that this thread is going to be destroyed
  646. // NOTE: here we assume that using the m_pHandler pointer is safe,
  647. // (in this case this is assured by the MyFrame destructor)
  648. wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_COMPLETED));
  649. return (wxThread::ExitCode)0; // success
  650. }
  651. MyThread::~MyThread()
  652. {
  653. wxCriticalSectionLocker enter(m_pHandler->m_pThreadCS);
  654. // the thread is being destroyed; make sure not to leave dangling pointers around
  655. m_pHandler->m_pThread = NULL;
  656. }
  657. void MyFrame::OnThreadCompletion(wxThreadEvent&)
  658. {
  659. wxMessageOutputDebug().Printf("MYFRAME: MyThread exited!\n");
  660. }
  661. void MyFrame::OnThreadUpdate(wxThreadEvent&)
  662. {
  663. wxMessageOutputDebug().Printf("MYFRAME: MyThread update...\n");
  664. }
  665. void MyFrame::DoPauseThread()
  666. {
  667. // anytime we access the m_pThread pointer we must ensure that it won't
  668. // be modified in the meanwhile; since only a single thread may be
  669. // inside a given critical section at a given time, the following code
  670. // is safe:
  671. wxCriticalSectionLocker enter(m_pThreadCS);
  672. if (m_pThread) // does the thread still exist?
  673. {
  674. // without a critical section, once reached this point it may happen
  675. // that the OS scheduler gives control to the MyThread::Entry() function,
  676. // which in turn may return (because it completes its work) making
  677. // invalid the m_pThread pointer
  678. if (m_pThread->Pause() != wxTHREAD_NO_ERROR )
  679. wxLogError("Can't pause the thread!");
  680. }
  681. }
  682. void MyFrame::OnClose(wxCloseEvent&)
  683. {
  684. {
  685. wxCriticalSectionLocker enter(m_pThreadCS);
  686. if (m_pThread) // does the thread still exist?
  687. {
  688. wxMessageOutputDebug().Printf("MYFRAME: deleting thread");
  689. if (m_pThread->Delete() != wxTHREAD_NO_ERROR )
  690. wxLogError("Can't delete the thread!");
  691. }
  692. } // exit from the critical section to give the thread
  693. // the possibility to enter its destructor
  694. // (which is guarded with m_pThreadCS critical section!)
  695. while (1)
  696. {
  697. { // was the ~MyThread() function executed?
  698. wxCriticalSectionLocker enter(m_pThreadCS);
  699. if (!m_pThread) break;
  700. }
  701. // wait for thread completion
  702. wxThread::This()->Sleep(1);
  703. }
  704. Destroy();
  705. }
  706. @endcode
  707. For a more detailed and comprehensive example, see @sample{thread}.
  708. For a simpler way to share data and synchronization objects between
  709. the main and the secondary thread see wxThreadHelper.
  710. Conversely, @b joinable threads do not delete themselves when they are done
  711. processing and as such are safe to create on the stack. Joinable threads
  712. also provide the ability for one to get value it returned from Entry()
  713. through Wait().
  714. You shouldn't hurry to create all the threads joinable, however, because this
  715. has a disadvantage as well: you @b must Wait() for a joinable thread or the
  716. system resources used by it will never be freed, and you also must delete the
  717. corresponding wxThread object yourself if you did not create it on the stack.
  718. In contrast, detached threads are of the "fire-and-forget" kind: you only have
  719. to start a detached thread and it will terminate and destroy itself.
  720. @section thread_deletion wxThread Deletion
  721. Regardless of whether it has terminated or not, you should call Wait() on a
  722. @b joinable thread to release its memory, as outlined in @ref thread_types.
  723. If you created a joinable thread on the heap, remember to delete it manually
  724. with the @c delete operator or similar means as only detached threads handle
  725. this type of memory management.
  726. Since @b detached threads delete themselves when they are finished processing,
  727. you should take care when calling a routine on one. If you are certain the
  728. thread is still running and would like to end it, you may call Delete()
  729. to gracefully end it (which implies that the thread will be deleted after
  730. that call to Delete()). It should be implied that you should @b never attempt
  731. to delete a detached thread with the @c delete operator or similar means.
  732. As mentioned, Wait() or Delete() functions attempt to gracefully terminate a
  733. joinable and a detached thread, respectively. They do this by waiting until
  734. the thread in question calls TestDestroy() or ends processing (i.e. returns
  735. from wxThread::Entry).
  736. Obviously, if the thread does call TestDestroy() and does not end, the
  737. thread which called Wait() or Delete() will come to halt.
  738. This is why it's important to call TestDestroy() in the Entry() routine of
  739. your threads as often as possible and immediately exit when it returns @true.
  740. As a last resort you can end the thread immediately through Kill(). It is
  741. strongly recommended that you do not do this, however, as it does not free
  742. the resources associated with the object (although the wxThread object of
  743. detached threads will still be deleted) and could leave the C runtime
  744. library in an undefined state.
  745. @section thread_secondary wxWidgets Calls in Secondary Threads
  746. All threads other than the "main application thread" (the one running
  747. wxApp::OnInit() or the one your main function runs in, for example) are
  748. considered "secondary threads".
  749. GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe
  750. at all in secondary threads and could end your application prematurely.
  751. This is due to several reasons, including the underlying native API and
  752. the fact that wxThread does not run a GUI event loop similar to other APIs
  753. as MFC.
  754. A workaround for some wxWidgets ports is calling wxMutexGUIEnter()
  755. before any GUI calls and then calling wxMutexGUILeave() afterwords.
  756. However, the recommended way is to simply process the GUI calls in the main
  757. thread through an event that is posted by wxQueueEvent().
  758. This does not imply that calls to these classes are thread-safe, however,
  759. as most wxWidgets classes are not thread-safe, including wxString.
  760. @section thread_poll Don't Poll a wxThread
  761. A common problem users experience with wxThread is that in their main thread
  762. they will check the thread every now and then to see if it has ended through
  763. IsRunning(), only to find that their application has run into problems
  764. because the thread is using the default behaviour (i.e. it's @b detached) and
  765. has already deleted itself.
  766. Naturally, they instead attempt to use joinable threads in place of the previous
  767. behaviour. However, polling a wxThread for when it has ended is in general a
  768. bad idea - in fact calling a routine on any running wxThread should be avoided
  769. if possible. Instead, find a way to notify yourself when the thread has ended.
  770. Usually you only need to notify the main thread, in which case you can
  771. post an event to it via wxQueueEvent().
  772. In the case of secondary threads you can call a routine of another class
  773. when the thread is about to complete processing and/or set the value of
  774. a variable, possibly using mutexes (see wxMutex) and/or other synchronization
  775. means if necessary.
  776. @library{wxbase}
  777. @category{threading}
  778. @see wxThreadHelper, wxMutex, wxCondition, wxCriticalSection,
  779. @ref overview_thread
  780. */
  781. class wxThread
  782. {
  783. public:
  784. /**
  785. The return type for the thread functions.
  786. */
  787. typedef void* ExitCode;
  788. /**
  789. This constructor creates a new detached (default) or joinable C++
  790. thread object. It does not create or start execution of the real thread -
  791. for this you should use the Run() method.
  792. The possible values for @a kind parameters are:
  793. - @b wxTHREAD_DETACHED - Creates a detached thread.
  794. - @b wxTHREAD_JOINABLE - Creates a joinable thread.
  795. */
  796. wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
  797. /**
  798. The destructor frees the resources associated with the thread.
  799. Notice that you should never delete a detached thread -- you may only call
  800. Delete() on it or wait until it terminates (and auto destructs) itself.
  801. Because the detached threads delete themselves, they can only be allocated on the heap.
  802. Joinable threads should be deleted explicitly. The Delete() and Kill() functions
  803. will not delete the C++ thread object. It is also safe to allocate them on stack.
  804. */
  805. virtual ~wxThread();
  806. /**
  807. Creates a new thread.
  808. The thread object is created in the suspended state, and you should call Run()
  809. to start running it. You may optionally specify the stack size to be allocated
  810. to it (Ignored on platforms that don't support setting it explicitly,
  811. eg. Unix system without @c pthread_attr_setstacksize).
  812. If you do not specify the stack size, the system's default value is used.
  813. @note
  814. It is not necessary to call this method since 2.9.5, Run() will create
  815. the thread internally. You only need to call Create() if you need to do
  816. something with the thread (e.g. pass its ID to an external library)
  817. before it starts.
  818. @warning
  819. It is a good idea to explicitly specify a value as systems'
  820. default values vary from just a couple of KB on some systems (BSD and
  821. OS/2 systems) to one or several MB (Windows, Solaris, Linux).
  822. So, if you have a thread that requires more than just a few KB of memory, you
  823. will have mysterious problems on some platforms but not on the common ones.
  824. On the other hand, just indicating a large stack size by default will give you
  825. performance issues on those systems with small default stack since those
  826. typically use fully committed memory for the stack.
  827. On the contrary, if you use a lot of threads (say several hundred),
  828. virtual address space can get tight unless you explicitly specify a
  829. smaller amount of thread stack space for each thread.
  830. @return One of:
  831. - @b wxTHREAD_NO_ERROR - No error.
  832. - @b wxTHREAD_NO_RESOURCE - There were insufficient resources to create the thread.
  833. - @b wxTHREAD_NO_RUNNING - The thread is already running
  834. */
  835. wxThreadError Create(unsigned int stackSize = 0);
  836. /**
  837. Calling Delete() gracefully terminates a @b detached thread, either when
  838. the thread calls TestDestroy() or when it finishes processing.
  839. @param rc
  840. The thread exit code, if rc is not NULL.
  841. @param waitMode
  842. As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
  843. should be used as the wait mode even although currently
  844. wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
  845. new in wxWidgets 2.9.2.
  846. @note
  847. This function works on a joinable thread but in that case makes
  848. the TestDestroy() function of the thread return @true and then
  849. waits for its completion (i.e. it differs from Wait() because
  850. it asks the thread to terminate before waiting).
  851. See @ref thread_deletion for a broader explanation of this routine.
  852. */
  853. wxThreadError Delete(ExitCode *rc = NULL,
  854. wxThreadWait waitMode = wxTHREAD_WAIT_BLOCK);
  855. /**
  856. Returns the number of system CPUs or -1 if the value is unknown.
  857. For multi-core systems the returned value is typically the total number
  858. of @e cores, since the OS usually abstract a single N-core CPU
  859. as N different cores.
  860. @see SetConcurrency()
  861. */
  862. static int GetCPUCount();
  863. /**
  864. Returns the platform specific thread ID of the current thread as a long.
  865. This can be used to uniquely identify threads, even if they are not wxThreads.
  866. @see GetMainId()
  867. */
  868. static wxThreadIdType GetCurrentId();
  869. /**
  870. Gets the thread identifier: this is a platform dependent number that uniquely
  871. identifies the thread throughout the system during its existence
  872. (i.e.\ the thread identifiers may be reused).
  873. */
  874. wxThreadIdType GetId() const;
  875. /**
  876. Returns the thread kind as it was given in the ctor.
  877. @since 2.9.0
  878. */
  879. wxThreadKind GetKind() const;
  880. /**
  881. Returns the thread ID of the main thread.
  882. @see IsMain()
  883. @since 2.9.1
  884. */
  885. static wxThreadIdType GetMainId();
  886. /**
  887. Gets the priority of the thread, between 0 (lowest) and 100 (highest).
  888. @see SetPriority()
  889. */
  890. unsigned int GetPriority() const;
  891. /**
  892. Returns @true if the thread is alive (i.e.\ started and not terminating).
  893. Note that this function can only safely be used with joinable threads, not
  894. detached ones as the latter delete themselves and so when the real thread is
  895. no longer alive, it is not possible to call this function because
  896. the wxThread object no longer exists.
  897. */
  898. bool IsAlive() const;
  899. /**
  900. Returns @true if the thread is of the detached kind, @false if it is a
  901. joinable one.
  902. */
  903. bool IsDetached() const;
  904. /**
  905. Returns @true if the calling thread is the main application thread.
  906. Main thread in the context of wxWidgets is the one which initialized
  907. the library.
  908. @see GetMainId(), GetCurrentId()
  909. */
  910. static bool IsMain();
  911. /**
  912. Returns @true if the thread is paused.
  913. */
  914. bool IsPaused() const;
  915. /**
  916. Returns @true if the thread is running.
  917. This method may only be safely used for joinable threads, see the remark in
  918. IsAlive().
  919. */
  920. bool IsRunning() const;
  921. /**
  922. Immediately terminates the target thread.
  923. @b "This function is dangerous and should be used with extreme care"
  924. (and not used at all whenever possible)! The resources allocated to the
  925. thread will not be freed and the state of the C runtime library may become
  926. inconsistent. Use Delete() for detached threads or Wait() for joinable
  927. threads instead.
  928. For detached threads Kill() will also delete the associated C++ object.
  929. However this will not happen for joinable threads and this means that you will
  930. still have to delete the wxThread object yourself to avoid memory leaks.
  931. In neither case OnExit() of the dying thread will be called, so no
  932. thread-specific cleanup will be performed.
  933. This function can only be called from another thread context, i.e. a thread
  934. cannot kill itself.
  935. It is also an error to call this function for a thread which is not running or
  936. paused (in the latter case, the thread will be resumed first) -- if you do it,
  937. a @b wxTHREAD_NOT_RUNNING error will be returned.
  938. */
  939. wxThreadError Kill();
  940. /**
  941. Suspends the thread.
  942. Under some implementations (Win32), the thread is suspended immediately,
  943. under others it will only be suspended when it calls TestDestroy() for
  944. the next time (hence, if the thread doesn't call it at all, it won't be
  945. suspended).
  946. This function can only be called from another thread context.
  947. */
  948. wxThreadError Pause();
  949. /**
  950. Resumes a thread suspended by the call to Pause().
  951. This function can only be called from another thread context.
  952. */
  953. wxThreadError Resume();
  954. /**
  955. Starts the thread execution.
  956. Note that once you Run() a @b detached thread, @e any function call you do
  957. on the thread pointer (you must allocate it on the heap) is @e "unsafe";
  958. i.e. the thread may have terminated at any moment after Run() and your pointer
  959. may be dangling. See @ref thread_types for an example of safe manipulation
  960. of detached threads.
  961. This function can only be called from another thread context.
  962. Finally, note that once a thread has completed and its Entry() function
  963. returns, you cannot call Run() on it again (an assert will fail in debug
  964. builds or @c wxTHREAD_RUNNING will be returned in release builds).
  965. */
  966. wxThreadError Run();
  967. /**
  968. Sets the thread concurrency level for this process.
  969. This is, roughly, the number of threads that the system tries to schedule
  970. to run in parallel.
  971. The value of 0 for @a level may be used to set the default one.
  972. @return @true on success or @false otherwise (for example, if this function is
  973. not implemented for this platform -- currently everything except Solaris).
  974. */
  975. static bool SetConcurrency(size_t level);
  976. /**
  977. Sets the priority of the thread, between 0 (lowest) and 100 (highest).
  978. The following symbolic constants can be used in addition to raw
  979. values in 0..100 range:
  980. - @c wxPRIORITY_MIN: 0
  981. - @c wxPRIORITY_DEFAULT: 50
  982. - @c wxPRIORITY_MAX: 100
  983. */
  984. void SetPriority(unsigned int priority);
  985. /**
  986. Pauses the thread execution for the given amount of time.
  987. This is the same as wxMilliSleep().
  988. */
  989. static void Sleep(unsigned long milliseconds);
  990. /**
  991. This function should be called periodically by the thread to ensure that
  992. calls to Pause() and Delete() will work.
  993. If it returns @true, the thread should exit as soon as possible.
  994. Notice that under some platforms (POSIX), implementation of Pause() also
  995. relies on this function being called, so not calling it would prevent
  996. both stopping and suspending thread from working.
  997. */
  998. virtual bool TestDestroy();
  999. /**
  1000. Return the thread object for the calling thread.
  1001. @NULL is returned if the calling thread is the main (GUI) thread, but
  1002. IsMain() should be used to test whether the thread is really the main one
  1003. because @NULL may also be returned for the thread not created with wxThread
  1004. class. Generally speaking, the return value for such a thread is undefined.
  1005. */
  1006. static wxThread* This();
  1007. /**
  1008. Waits for a @b joinable thread to terminate and returns the value the thread
  1009. returned from Entry() or @c "(ExitCode)-1" on error. Notice that, unlike
  1010. Delete(), this function doesn't cancel the thread in any way so the caller
  1011. waits for as long as it takes to the thread to exit.
  1012. You can only Wait() for @b joinable (not detached) threads.
  1013. This function can only be called from another thread context.
  1014. @param flags
  1015. As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
  1016. should be used as the wait mode even although currently
  1017. wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
  1018. new in wxWidgets 2.9.2.
  1019. See @ref thread_deletion for a broader explanation of this routine.
  1020. */
  1021. ExitCode Wait(wxThreadWait flags = wxTHREAD_WAIT_BLOCK);
  1022. /**
  1023. Give the rest of the thread's time-slice to the system allowing the other
  1024. threads to run.
  1025. Note that using this function is @b strongly discouraged, since in
  1026. many cases it indicates a design weakness of your threading model
  1027. (as does using Sleep() functions).
  1028. Threads should use the CPU in an efficient manner, i.e. they should
  1029. do their current work efficiently, then as soon as the work is done block
  1030. on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
  1031. get signalled e.g. by other threads or a user device once further thread
  1032. work is available.
  1033. Using Yield() or Sleep() indicates polling-type behaviour, since we're
  1034. fuzzily giving up our timeslice and wait until sometime later we'll get
  1035. reactivated, at which time we realize that there isn't really much to do
  1036. and Yield() again...
  1037. The most critical characteristic of Yield() is that it's operating system
  1038. specific: there may be scheduler changes which cause your thread to not
  1039. wake up relatively soon again, but instead many seconds later,
  1040. causing huge performance issues for your application.
  1041. <strong>
  1042. With a well-behaving, CPU-efficient thread the operating system is likely
  1043. to properly care for its reactivation the moment it needs it, whereas with
  1044. non-deterministic, Yield-using threads all bets are off and the system
  1045. scheduler is free to penalize them drastically</strong>, and this effect
  1046. gets worse with increasing system load due to less free CPU resources available.
  1047. You may refer to various Linux kernel @c sched_yield discussions for more
  1048. information.
  1049. See also Sleep().
  1050. */
  1051. static void Yield();
  1052. protected:
  1053. /**
  1054. This is the entry point of the thread.
  1055. This function is pure virtual and must be implemented by any derived class.
  1056. The thread execution will start here.
  1057. The returned value is the thread exit code which is only useful for
  1058. joinable threads and is the value returned by Wait().
  1059. This function is called by wxWidgets itself and should never be called
  1060. directly.
  1061. */
  1062. virtual ExitCode Entry() = 0;
  1063. /**
  1064. This is a protected function of the wxThread class and thus can only be called
  1065. from a derived class. It also can only be called in the context of this
  1066. thread, i.e. a thread can only exit from itself, not from another thread.
  1067. This function will terminate the OS thread (i.e. stop the associated path of
  1068. execution) and also delete the associated C++ object for detached threads.
  1069. OnExit() will be called just before exiting.
  1070. */
  1071. void Exit(ExitCode exitcode = 0);
  1072. private:
  1073. /**
  1074. Called when the thread exits.
  1075. This function is called in the context of the thread associated with the
  1076. wxThread object, not in the context of the main thread.
  1077. This function will not be called if the thread was @ref Kill() killed.
  1078. This function should never be called directly.
  1079. */
  1080. virtual void OnExit();
  1081. };
  1082. /** See wxSemaphore. */
  1083. enum wxSemaError
  1084. {
  1085. wxSEMA_NO_ERROR = 0,
  1086. wxSEMA_INVALID, //!< semaphore hasn't been initialized successfully
  1087. wxSEMA_BUSY, //!< returned by TryWait() if Wait() would block
  1088. wxSEMA_TIMEOUT, //!< returned by WaitTimeout()
  1089. wxSEMA_OVERFLOW, //!< Post() would increase counter past the max
  1090. wxSEMA_MISC_ERROR
  1091. };
  1092. /**
  1093. @class wxSemaphore
  1094. wxSemaphore is a counter limiting the number of threads concurrently accessing
  1095. a shared resource. This counter is always between 0 and the maximum value
  1096. specified during the semaphore creation. When the counter is strictly greater
  1097. than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
  1098. counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
  1099. block and only return when the semaphore counter becomes strictly positive
  1100. again as the result of calling wxSemaphore::Post which increments the counter.
  1101. In general, semaphores are useful to restrict access to a shared resource
  1102. which can only be accessed by some fixed number of clients at the same time.
  1103. For example, when modeling a hotel reservation system a semaphore with the counter
  1104. equal to the total number of available rooms could be created. Each time a room
  1105. is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
  1106. and each time a room is freed it should be released by calling wxSemaphore::Post.
  1107. @library{wxbase}
  1108. @category{threading}
  1109. */
  1110. class wxSemaphore
  1111. {
  1112. public:
  1113. /**
  1114. Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
  1115. there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
  1116. mutex (but unlike a mutex it can be released by a thread different from the one
  1117. which acquired it).
  1118. @a initialcount is the initial value of the semaphore which must be between
  1119. 0 and @a maxcount (if it is not set to 0).
  1120. */
  1121. wxSemaphore(int initialcount = 0, int maxcount = 0);
  1122. /**
  1123. Destructor is not virtual, don't use this class polymorphically.
  1124. */
  1125. ~wxSemaphore();
  1126. /**
  1127. Increments the semaphore count and signals one of the waiting
  1128. threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
  1129. would increase the counter past the maximum.
  1130. @return One of:
  1131. - wxSEMA_NO_ERROR: There was no error.
  1132. - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
  1133. - wxSEMA_OVERFLOW: Post() would increase counter past the max.
  1134. - wxSEMA_MISC_ERROR: Miscellaneous error.
  1135. */
  1136. wxSemaError Post();
  1137. /**
  1138. Same as Wait(), but returns immediately.
  1139. @return One of:
  1140. - wxSEMA_NO_ERROR: There was no error.
  1141. - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
  1142. - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
  1143. - wxSEMA_MISC_ERROR: Miscellaneous error.
  1144. */
  1145. wxSemaError TryWait();
  1146. /**
  1147. Wait indefinitely until the semaphore count becomes strictly positive
  1148. and then decrement it and return.
  1149. @return One of:
  1150. - wxSEMA_NO_ERROR: There was no error.
  1151. - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
  1152. - wxSEMA_MISC_ERROR: Miscellaneous error.
  1153. */
  1154. wxSemaError Wait();
  1155. /**
  1156. Same as Wait(), but with a timeout limit.
  1157. @return One of:
  1158. - wxSEMA_NO_ERROR: There was no error.
  1159. - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
  1160. - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
  1161. - wxSEMA_MISC_ERROR: Miscellaneous error.
  1162. */
  1163. wxSemaError WaitTimeout(unsigned long timeout_millis);
  1164. };
  1165. /**
  1166. @class wxMutexLocker
  1167. This is a small helper class to be used with wxMutex objects.
  1168. A wxMutexLocker acquires a mutex lock in the constructor and releases
  1169. (or unlocks) the mutex in the destructor making it much more difficult to
  1170. forget to release a mutex (which, in general, will promptly lead to serious
  1171. problems). See wxMutex for an example of wxMutexLocker usage.
  1172. @library{wxbase}
  1173. @category{threading}
  1174. @see wxMutex, wxCriticalSectionLocker
  1175. */
  1176. class wxMutexLocker
  1177. {
  1178. public:
  1179. /**
  1180. Constructs a wxMutexLocker object associated with mutex and locks it.
  1181. Call IsOk() to check if the mutex was successfully locked.
  1182. */
  1183. wxMutexLocker(wxMutex& mutex);
  1184. /**
  1185. Destructor releases the mutex if it was successfully acquired in the ctor.
  1186. */
  1187. ~wxMutexLocker();
  1188. /**
  1189. Returns @true if mutex was acquired in the constructor, @false otherwise.
  1190. */
  1191. bool IsOk() const;
  1192. };
  1193. /**
  1194. The possible wxMutex kinds.
  1195. */
  1196. enum wxMutexType
  1197. {
  1198. /** Normal non-recursive mutex: try to always use this one. */
  1199. wxMUTEX_DEFAULT,
  1200. /** Recursive mutex: don't use these ones with wxCondition. */
  1201. wxMUTEX_RECURSIVE
  1202. };
  1203. /**
  1204. The possible wxMutex errors.
  1205. */
  1206. enum wxMutexError
  1207. {
  1208. /** The operation completed successfully. */
  1209. wxMUTEX_NO_ERROR = 0,
  1210. /** The mutex hasn't been initialized. */
  1211. wxMUTEX_INVALID,
  1212. /** The mutex is already locked by the calling thread. */
  1213. wxMUTEX_DEAD_LOCK,
  1214. /** The mutex is already locked by another thread. */
  1215. wxMUTEX_BUSY,
  1216. /** An attempt to unlock a mutex which is not locked. */
  1217. wxMUTEX_UNLOCKED,
  1218. /** wxMutex::LockTimeout() has timed out. */
  1219. wxMUTEX_TIMEOUT,
  1220. /** Any other error */
  1221. wxMUTEX_MISC_ERROR
  1222. };
  1223. /**
  1224. @class wxMutex
  1225. A mutex object is a synchronization object whose state is set to signaled when
  1226. it is not owned by any thread, and nonsignaled when it is owned. Its name comes
  1227. from its usefulness in coordinating mutually-exclusive access to a shared
  1228. resource as only one thread at a time can own a mutex object.
  1229. Mutexes may be recursive in the sense that a thread can lock a mutex which it
  1230. had already locked before (instead of dead locking the entire process in this
  1231. situation by starting to wait on a mutex which will never be released while the
  1232. thread is waiting) but using them is not recommended under Unix and they are
  1233. @b not recursive by default. The reason for this is that recursive
  1234. mutexes are not supported by all Unix flavours and, worse, they cannot be used
  1235. with wxCondition.
  1236. For example, when several threads use the data stored in the linked list,
  1237. modifications to the list should only be allowed to one thread at a time
  1238. because during a new node addition the list integrity is temporarily broken
  1239. (this is also called @e program @e invariant).
  1240. @code
  1241. // this variable has an "s_" prefix because it is static: seeing an "s_" in
  1242. // a multithreaded program is in general a good sign that you should use a
  1243. // mutex (or a critical section)
  1244. static wxMutex *s_mutexProtectingTheGlobalData;
  1245. // we store some numbers in this global array which is presumably used by
  1246. // several threads simultaneously
  1247. wxArrayInt s_data;
  1248. void MyThread::AddNewNode(int num)
  1249. {
  1250. // ensure that no other thread accesses the list
  1251. s_mutexProtectingTheGlobalList->Lock();
  1252. s_data.Add(num);
  1253. s_mutexProtectingTheGlobalList->Unlock();
  1254. }
  1255. // return true if the given number is greater than all array elements
  1256. bool MyThread::IsGreater(int num)
  1257. {
  1258. // before using the list we must acquire the mutex
  1259. wxMutexLocker lock(s_mutexProtectingTheGlobalData);
  1260. size_t count = s_data.Count();
  1261. for ( size_t n = 0; n < count; n++ )
  1262. {
  1263. if ( s_data[n] > num )
  1264. return false;
  1265. }
  1266. return true;
  1267. }
  1268. @endcode
  1269. Notice how wxMutexLocker was used in the second function to ensure that the
  1270. mutex is unlocked in any case: whether the function returns true or false
  1271. (because the destructor of the local object @e lock is always called).
  1272. Using this class instead of directly using wxMutex is, in general, safer
  1273. and is even more so if your program uses C++ exceptions.
  1274. @library{wxbase}
  1275. @category{threading}
  1276. @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
  1277. */
  1278. class wxMutex
  1279. {
  1280. public:
  1281. /**
  1282. Default constructor.
  1283. */
  1284. wxMutex(wxMutexType type = wxMUTEX_DEFAULT);
  1285. /**
  1286. Destroys the wxMutex object.
  1287. */
  1288. ~wxMutex();
  1289. /**
  1290. Locks the mutex object.
  1291. This is equivalent to LockTimeout() with infinite timeout.
  1292. Note that if this mutex is already locked by the caller thread,
  1293. this function doesn't block but rather immediately returns.
  1294. @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
  1295. */
  1296. wxMutexError Lock();
  1297. /**
  1298. Try to lock the mutex object during the specified time interval.
  1299. @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
  1300. */
  1301. wxMutexError LockTimeout(unsigned long msec);
  1302. /**
  1303. Tries to lock the mutex object. If it can't, returns immediately with an error.
  1304. @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
  1305. */
  1306. wxMutexError TryLock();
  1307. /**
  1308. Unlocks the mutex object.
  1309. @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
  1310. */
  1311. wxMutexError Unlock();
  1312. };
  1313. // ============================================================================
  1314. // Global functions/macros
  1315. // ============================================================================
  1316. /** @addtogroup group_funcmacro_thread */
  1317. //@{
  1318. /**
  1319. This macro declares a (static) critical section object named @a cs if
  1320. @c wxUSE_THREADS is 1 and does nothing if it is 0.
  1321. @header{wx/thread.h}
  1322. */
  1323. #define wxCRIT_SECT_DECLARE(cs)
  1324. /**
  1325. This macro declares a critical section object named @a cs if
  1326. @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
  1327. the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
  1328. declare a class or struct member which explains its name.
  1329. @header{wx/thread.h}
  1330. */
  1331. #define wxCRIT_SECT_DECLARE_MEMBER(cs)
  1332. /**
  1333. This macro creates a wxCriticalSectionLocker named @a name and associated
  1334. with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
  1335. if it is 0.
  1336. @header{wx/thread.h}
  1337. */
  1338. #define wxCRIT_SECT_LOCKER(name, cs)
  1339. /**
  1340. This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
  1341. creates a static critical section object and also the lock object
  1342. associated with it. Because of this, it can be only used inside a function,
  1343. not at global scope. For example:
  1344. @code
  1345. int IncCount()
  1346. {
  1347. static int s_counter = 0;
  1348. wxCRITICAL_SECTION(counter);
  1349. return ++s_counter;
  1350. }
  1351. @endcode
  1352. Note that this example assumes that the function is called the first time
  1353. from the main thread so that the critical section object is initialized
  1354. correctly by the time other threads start calling it, if this is not the
  1355. case this approach can @b not be used and the critical section must be made
  1356. a global instead.
  1357. @header{wx/thread.h}
  1358. */
  1359. #define wxCRITICAL_SECTION(name)
  1360. /**
  1361. This macro is equivalent to
  1362. @ref wxCriticalSection::Leave "critical_section.Leave()" if
  1363. @c wxUSE_THREADS is 1 and does nothing if it is 0.
  1364. @header{wx/thread.h}
  1365. */
  1366. #define wxLEAVE_CRIT_SECT(critical_section)
  1367. /**
  1368. This macro is equivalent to
  1369. @ref wxCriticalSection::Enter "critical_section.Enter()" if
  1370. @c wxUSE_THREADS is 1 and does nothing if it is 0.
  1371. @header{wx/thread.h}
  1372. */
  1373. #define wxENTER_CRIT_SECT(critical_section)
  1374. /**
  1375. Returns @true if this thread is the main one. Always returns @true if
  1376. @c wxUSE_THREADS is 0.
  1377. @header{wx/thread.h}
  1378. */
  1379. bool wxIsMainThread();
  1380. /**
  1381. This function must be called when any thread other than the main GUI thread
  1382. wants to get access to the GUI library. This function will block the
  1383. execution of the calling thread until the main thread (or any other thread
  1384. holding the main GUI lock) leaves the GUI library and no other thread will
  1385. enter the GUI library until the calling thread calls wxMutexGuiLeave().
  1386. Typically, these functions are used like this:
  1387. @code
  1388. void MyThread::Foo(void)
  1389. {
  1390. // before doing any GUI calls we must ensure that
  1391. // this thread is the only one doing it!
  1392. wxMutexGuiEnter();
  1393. // Call GUI here:
  1394. my_window->DrawSomething();
  1395. wxMutexGuiLeave();
  1396. }
  1397. @endcode
  1398. This function is only defined on platforms which support preemptive
  1399. threads and only works under some ports (wxMSW currently).
  1400. @note Under GTK, no creation of top-level windows is allowed in any thread
  1401. but the main one.
  1402. @header{wx/thread.h}
  1403. */
  1404. void wxMutexGuiEnter();
  1405. /**
  1406. This function is only defined on platforms which support preemptive
  1407. threads.
  1408. @see wxMutexGuiEnter()
  1409. @header{wx/thread.h}
  1410. */
  1411. void wxMutexGuiLeave();
  1412. //@}