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