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