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