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