1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of all thread-related wxWidgets classes
4 // Author: wxWidgets team
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
10 /** See wxCondition. */
15 wxCOND_TIMEOUT
, //!< WaitTimeout() has timed out
23 wxCondition variables correspond to pthread conditions or to Win32 event objects.
24 They may be used in a multithreaded application to wait until the given condition
25 becomes @true which happens when the condition becomes signaled.
27 For example, if a worker thread is doing some long task and another thread has
28 to wait until it is finished, the latter thread will wait on the condition
29 object and the worker thread will signal it on exit (this example is not
30 perfect because in this particular case it would be much better to just
31 wxThread::Wait for the worker thread, but if there are several worker threads
32 it already makes much more sense).
34 Note that a call to wxCondition::Signal may happen before the other thread calls
35 wxCondition::Wait and, just as with the pthread conditions, the signal is then
36 lost and so if you want to be sure that you don't miss it you must keep the
37 mutex associated with the condition initially locked and lock it again before calling
38 wxCondition::Signal. Of course, this means that this call is going to block
39 until wxCondition::Wait is called by another thread.
41 @section condition_example Example
43 This example shows how a main thread may launch a worker thread which starts
44 running and then waits until the main thread signals it to continue:
47 class MySignallingThread : public wxThread
50 MySignallingThread(wxMutex *mutex, wxCondition *condition)
53 m_condition = condition;
58 virtual ExitCode Entry()
62 // tell the other(s) thread(s) that we're about to terminate: we must
63 // lock the mutex first or we might signal the condition before the
64 // waiting threads start waiting on it!
65 wxMutexLocker lock(*m_mutex);
66 m_condition->Broadcast(); // same as Signal() here -- one waiter only
72 wxCondition *m_condition;
79 wxCondition condition(mutex);
81 // the mutex should be initially locked
84 // create and run the thread but notice that it won't be able to
85 // exit (and signal its exit) before we unlock the mutex below
86 MySignallingThread *thread = new MySignallingThread(&mutex, &condition);
90 // wait for the thread termination: Wait() atomically unlocks the mutex
91 // which allows the thread to continue and starts waiting
99 Of course, here it would be much better to simply use a joinable thread and
100 call wxThread::Wait on it, but this example does illustrate the importance of
101 properly locking the mutex when using wxCondition.
106 @see wxThread, wxMutex
112 Default and only constructor.
113 The @a mutex must be locked by the caller before calling Wait() function.
114 Use IsOk() to check if the object was successfully initialized.
116 wxCondition(wxMutex
& mutex
);
119 Destroys the wxCondition object.
121 The destructor is not virtual so this class should not be used polymorphically.
126 Broadcasts to all waiting threads, waking all of them up.
128 Note that this method may be called whether the mutex associated with
129 this condition is locked or not.
133 wxCondError
Broadcast();
136 Returns @true if the object had been initialized successfully, @false
137 if an error occurred.
142 Signals the object waking up at most one thread.
144 If several threads are waiting on the same condition, the exact thread
145 which is woken up is undefined. If no threads are waiting, the signal is
146 lost and the condition would have to be signalled again to wake up any
147 thread which may start waiting on it later.
149 Note that this method may be called whether the mutex associated with this
150 condition is locked or not.
154 wxCondError
Signal();
157 Waits until the condition is signalled.
159 This method atomically releases the lock on the mutex associated with this
160 condition (this is why it must be locked prior to calling Wait()) and puts the
161 thread to sleep until Signal() or Broadcast() is called.
162 It then locks the mutex again and returns.
164 Note that even if Signal() had been called before Wait() without waking
165 up any thread, the thread would still wait for another one and so it is
166 important to ensure that the condition will be signalled after
167 Wait() or the thread may sleep forever.
169 @return Returns wxCOND_NO_ERROR on success, another value if an error occurred.
176 Waits until the condition is signalled or the timeout has elapsed.
178 This method is identical to Wait() except that it returns, with the
179 return code of @c wxCOND_TIMEOUT as soon as the given timeout expires.
182 Timeout in milliseconds
184 @return Returns wxCOND_NO_ERROR if the condition was signalled,
185 wxCOND_TIMEOUT if the timeout elapsed before this happened or
186 another error code from wxCondError enum.
188 wxCondError
WaitTimeout(unsigned long milliseconds
);
193 @class wxCriticalSectionLocker
195 This is a small helper class to be used with wxCriticalSection objects.
197 A wxCriticalSectionLocker enters the critical section in the constructor and
198 leaves it in the destructor making it much more difficult to forget to leave
199 a critical section (which, in general, will lead to serious and difficult
207 // gs_critSect is some (global) critical section guarding access to the
209 wxCriticalSectionLocker locker(gs_critSect);
226 Without wxCriticalSectionLocker, you would need to remember to manually leave
227 the critical section before each @c return.
232 @see wxCriticalSection, wxMutexLocker
234 class wxCriticalSectionLocker
238 Constructs a wxCriticalSectionLocker object associated with given
239 @a criticalsection and enters it.
241 wxCriticalSectionLocker(wxCriticalSection
& criticalsection
);
244 Destructor leaves the critical section.
246 ~wxCriticalSectionLocker();
252 @class wxThreadHelper
254 The wxThreadHelper class is a mix-in class that manages a single background
255 thread, either detached or joinable (see wxThread for the differences).
256 By deriving from wxThreadHelper, a class can implement the thread
257 code in its own wxThreadHelper::Entry() method and easily share data and
258 synchronization objects between the main thread and the worker thread.
260 Doing this prevents the awkward passing of pointers that is needed when the
261 original object in the main thread needs to synchronize with its worker thread
262 in its own wxThread derived object.
264 For example, wxFrame may need to make some calculations in a background thread
265 and then display the results of those calculations in the main window.
267 Ordinarily, a wxThread derived object would be created with the calculation
268 code implemented in wxThread::Entry. To access the inputs to the calculation,
269 the frame object would often need to pass a pointer to itself to the thread object.
270 Similarly, the frame object would hold a pointer to the thread object.
272 Shared data and synchronization objects could be stored in either object
273 though the object without the data would have to access the data through
275 However with wxThreadHelper the frame object and the thread object are
276 treated as the same object. Shared data and synchronization variables are
277 stored in the single object, eliminating a layer of indirection and the
282 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent);
284 class MyFrame : public wxFrame, public wxThreadHelper
290 // it's better to do any thread cleanup in the OnClose()
291 // event handler, rather than in the destructor.
292 // This is because the event loop for a top-level window is not
293 // active anymore when its destructor is called and if the thread
294 // sends events when ending, they won't be processed unless
295 // you ended the thread from OnClose.
296 // See @ref overview_windowdeletion for more info.
300 void DoStartALongTask();
301 void OnThreadUpdate(wxThreadEvent& evt);
302 void OnClose(wxCloseEvent& evt);
306 virtual wxThread::ExitCode Entry();
308 // the output data of the Entry() routine:
310 wxCriticalSection m_dataCS; // protects field above
312 wxDECLARE_EVENT_TABLE();
315 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent)
316 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
317 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_UPDATE, MyFrame::OnThreadUpdate)
318 EVT_CLOSE(MyFrame::OnClose)
321 void MyFrame::DoStartALongTask()
323 // we want to start a long task, but we don't want our GUI to block
324 // while it's executed, so we use a thread to do it.
325 if (CreateThread(wxTHREAD_JOINABLE) != wxTHREAD_NO_ERROR)
327 wxLogError("Could not create the worker thread!");
332 if (GetThread()->Run() != wxTHREAD_NO_ERROR)
334 wxLogError("Could not run the worker thread!");
339 wxThread::ExitCode MyFrame::Entry()
342 // this function gets executed in the secondary thread context!
346 // here we do our long task, periodically calling TestDestroy():
347 while (!GetThread()->TestDestroy())
349 // since this Entry() is implemented in MyFrame context we don't
350 // need any pointer to access the m_data, m_processedData, m_dataCS
351 // variables... very nice!
353 // this is an example of the generic structure of a download thread:
355 download_chunk(buffer, 1024); // this takes time...
358 // ensure no one reads m_data while we write it
359 wxCriticalSectionLocker lock(m_dataCS);
360 memcpy(m_data+offset, buffer, 1024);
365 // VERY IMPORTANT: do not call any GUI function inside this
366 // function; rather use wxQueueEvent():
367 wxQueueEvent(this, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
368 // we used pointer 'this' assuming it's safe; see OnClose()
371 // TestDestroy() returned true (which means the main thread asked us
372 // to terminate as soon as possible) or we ended the long task...
373 return (wxThread::ExitCode)0;
376 void MyFrame::OnClose(wxCloseEvent&)
378 // important: before terminating, we _must_ wait for our joinable
379 // thread to end, if it's running; in fact it uses variables of this
380 // instance and posts events to *this event handler
382 if (GetThread() && // DoStartALongTask() may have not been called
383 GetThread()->IsRunning())
389 void MyFrame::OnThreadUpdate(wxThreadEvent& evt)
391 // ...do something... e.g. m_pGauge->Pulse();
393 // read some parts of m_data just for fun:
394 wxCriticalSectionLocker lock(m_dataCS);
395 wxPrintf("%c", m_data[100]);
402 @see wxThread, wxThreadEvent
408 This constructor simply initializes internal member variables and tells
409 wxThreadHelper which type the thread internally managed should be.
411 wxThreadHelper(wxThreadKind kind
= wxTHREAD_JOINABLE
);
414 The destructor frees the resources associated with the thread, forcing
415 it to terminate (it uses wxThread::Kill function).
417 Because of the wxThread::Kill unsafety, you should always wait
418 (with wxThread::Wait) for joinable threads to end or call wxThread::Delete
419 on detached threads, instead of relying on this destructor for stopping
422 virtual ~wxThreadHelper();
425 This is the entry point of the thread.
427 This function is pure virtual and must be implemented by any derived class.
428 The thread execution will start here.
430 You'll typically want your Entry() to look like:
432 wxThread::ExitCode Entry()
434 while (!GetThread()->TestDestroy())
436 // ... do some work ...
441 if (HappenedStoppingError)
442 return (wxThread::ExitCode)1; // failure
445 return (wxThread::ExitCode)0; // success
449 The returned value is the thread exit code which is only useful for
450 joinable threads and is the value returned by @c "GetThread()->Wait()".
452 This function is called by wxWidgets itself and should never be called
455 virtual ExitCode
Entry() = 0;
458 Callback called by Delete() before actually deleting the thread.
460 This function can be overridden by the derived class to perform some
461 specific task when the thread is gracefully destroyed. Notice that it
462 will be executed in the context of the thread that called Delete() and
463 <b>not</b> in this thread's context.
465 TestDestroy() will be true for the thread before OnDelete() gets
472 virtual void OnDelete();
475 Callback called by Kill() before actually killing the thread.
477 This function can be overridden by the derived class to perform some
478 specific task when the thread is terminated. Notice that it will be
479 executed in the context of the thread that called Kill() and <b>not</b>
480 in this thread's context.
486 virtual void OnKill();
490 Use CreateThread() instead.
492 wxThreadError
Create(unsigned int stackSize
= 0);
495 Creates a new thread of the given @a kind.
497 The thread object is created in the suspended state, and you
498 should call @ref wxThread::Run "GetThread()->Run()" to start running it.
500 You may optionally specify the stack size to be allocated to it (ignored
501 on platforms that don't support setting it explicitly, e.g. Unix).
503 @return One of the ::wxThreadError enum values.
505 wxThreadError
CreateThread(wxThreadKind kind
= wxTHREAD_JOINABLE
,
506 unsigned int stackSize
= 0);
509 This is a public function that returns the wxThread object associated with
512 wxThread
* GetThread() const;
515 Returns the last type of thread given to the CreateThread() function
516 or to the constructor.
518 wxThreadKind
GetThreadKind() const;
522 Possible critical section types
525 enum wxCriticalSectionType
528 /** Recursive critical section under both Windows and Unix */
530 wxCRITSEC_NON_RECURSIVE
531 /** Non-recursive critical section under Unix, recursive under Windows */
535 @class wxCriticalSection
537 A critical section object is used for exactly the same purpose as a wxMutex.
538 The only difference is that under Windows platform critical sections are only
539 visible inside one process, while mutexes may be shared among processes,
540 so using critical sections is slightly more efficient.
542 The terminology is also slightly different: mutex may be locked (or acquired)
543 and unlocked (or released) while critical section is entered and left by the program.
545 Finally, you should try to use wxCriticalSectionLocker class whenever
546 possible instead of directly using wxCriticalSection for the same reasons
547 wxMutexLocker is preferable to wxMutex - please see wxMutex for an example.
552 @note Critical sections can be used before the wxWidgets library is fully
553 initialized. In particular, it's safe to create global
554 wxCriticalSection instances.
556 @see wxThread, wxCondition, wxCriticalSectionLocker
558 class wxCriticalSection
562 Default constructor initializes critical section object.
563 By default critical sections are recursive under Unix and Windows.
565 wxCriticalSection( wxCriticalSectionType critSecType
= wxCRITSEC_DEFAULT
);
568 Destructor frees the resources.
570 ~wxCriticalSection();
573 Enter the critical section (same as locking a mutex): if another thread
574 has already entered it, this call will block until the other thread
576 There is no error return for this function.
578 After entering the critical section protecting a data variable,
579 the thread running inside the critical section may safely use/modify it.
581 Note that entering the same critical section twice or more from the same
582 thread doesn't result in a deadlock; in this case in fact this function will
588 Try to enter the critical section (same as trying to lock a mutex).
589 If it can't, immediately returns false.
596 Leave the critical section allowing other threads use the global data
597 protected by it. There is no error return for this function.
603 The possible thread wait types.
610 No events are processed while waiting.
612 This is the default under all platforms except for wxMSW.
617 Yield for event dispatching while waiting.
619 This flag is dangerous as it exposes the program using it to unexpected
620 reentrancies in the same way as calling wxYield() function does so you
621 are strongly advised to avoid its use and not wait for the thread
622 termination from the main (GUI) thread at all to avoid making your
623 application unresponsive.
625 Also notice that this flag is not portable as it is only implemented in
626 wxMSW and simply ignored under the other platforms.
631 Default wait mode for wxThread::Wait() and wxThread::Delete().
633 For compatibility reasons, the default wait mode is currently
634 wxTHREAD_WAIT_YIELD if WXWIN_COMPATIBILITY_2_8 is defined (and it is
635 by default). However, as mentioned above, you're strongly encouraged to
636 not use wxTHREAD_WAIT_YIELD and pass wxTHREAD_WAIT_BLOCK to wxThread
639 wxTHREAD_WAIT_DEFAULT
= wxTHREAD_WAIT_YIELD
643 The possible thread kinds.
647 /** Detached thread */
650 /** Joinable thread */
655 The possible thread errors.
660 wxTHREAD_NO_ERROR
= 0,
662 /** No resource left to create a new thread. */
663 wxTHREAD_NO_RESOURCE
,
665 /** The thread is already running. */
668 /** The thread isn't running. */
669 wxTHREAD_NOT_RUNNING
,
671 /** Thread we waited for had to be killed. */
674 /** Some other error */
679 Defines the interval of priority
683 WXTHREAD_MIN_PRIORITY
= 0u,
684 WXTHREAD_DEFAULT_PRIORITY
= 50u,
685 WXTHREAD_MAX_PRIORITY
= 100u
692 A thread is basically a path of execution through a program.
693 Threads are sometimes called @e light-weight processes, but the fundamental difference
694 between threads and processes is that memory spaces of different processes are
695 separated while all threads share the same address space.
697 While it makes it much easier to share common data between several threads, it
698 also makes it much easier to shoot oneself in the foot, so careful use of
699 synchronization objects such as mutexes (see wxMutex) or critical sections
700 (see wxCriticalSection) is recommended.
701 In addition, don't create global thread objects because they allocate memory
702 in their constructor, which will cause problems for the memory checking system.
705 @section thread_types Types of wxThreads
707 There are two types of threads in wxWidgets: @e detached and @e joinable,
708 modeled after the POSIX thread API. This is different from the Win32 API
709 where all threads are joinable.
711 By default wxThreads in wxWidgets use the @b detached behaviour.
712 Detached threads delete themselves once they have completed, either by themselves
713 when they complete processing or through a call to Delete(), and thus
714 @b must be created on the heap (through the new operator, for example).
716 Typically you'll want to store the instances of the detached wxThreads you
717 allocate, so that you can call functions on them.
718 Because of their nature however you'll need to always use a critical section
722 // declare a new type of event, to be used by our MyThread class:
723 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent);
724 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent);
727 class MyThread : public wxThread
730 MyThread(MyFrame *handler)
731 : wxThread(wxTHREAD_DETACHED)
732 { m_pHandler = handler }
736 virtual ExitCode Entry();
740 class MyFrame : public wxFrame
746 // it's better to do any thread cleanup in the OnClose()
747 // event handler, rather than in the destructor.
748 // This is because the event loop for a top-level window is not
749 // active anymore when its destructor is called and if the thread
750 // sends events when ending, they won't be processed unless
751 // you ended the thread from OnClose.
752 // See @ref overview_windowdeletion for more info.
755 void DoStartThread();
756 void DoPauseThread();
758 // a resume routine would be nearly identic to DoPauseThread()
759 void DoResumeThread() { ... }
761 void OnThreadUpdate(wxThreadEvent&);
762 void OnThreadCompletion(wxThreadEvent&);
763 void OnClose(wxCloseEvent&);
767 wxCriticalSection m_pThreadCS; // protects the m_pThread pointer
769 wxDECLARE_EVENT_TABLE();
772 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
773 EVT_CLOSE(MyFrame::OnClose)
774 EVT_MENU(Minimal_Start, MyFrame::DoStartThread)
775 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_UPDATE, MyFrame::OnThreadUpdate)
776 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_COMPLETED, MyFrame::OnThreadCompletion)
779 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent)
780 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent)
782 void MyFrame::DoStartThread()
784 m_pThread = new MyThread(this);
786 if ( m_pThread->Create() != wxTHREAD_NO_ERROR )
788 wxLogError("Can't create the thread!");
794 if (m_pThread->Run() != wxTHREAD_NO_ERROR )
796 wxLogError("Can't create the thread!");
801 // after the call to wxThread::Run(), the m_pThread pointer is "unsafe":
802 // at any moment the thread may cease to exist (because it completes its work).
803 // To avoid dangling pointers OnThreadExit() will set m_pThread
804 // to NULL when the thread dies.
808 wxThread::ExitCode MyThread::Entry()
810 while (!TestDestroy())
812 // ... do a bit of work...
814 wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
817 // signal the event handler that this thread is going to be destroyed
818 // NOTE: here we assume that using the m_pHandler pointer is safe,
819 // (in this case this is assured by the MyFrame destructor)
820 wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_COMPLETED));
822 return (wxThread::ExitCode)0; // success
825 MyThread::~MyThread()
827 wxCriticalSectionLocker enter(m_pHandler->m_pThreadCS);
829 // the thread is being destroyed; make sure not to leave dangling pointers around
830 m_pHandler->m_pThread = NULL;
833 void MyFrame::OnThreadCompletion(wxThreadEvent&)
835 wxMessageOutputDebug().Printf("MYFRAME: MyThread exited!\n");
838 void MyFrame::OnThreadUpdate(wxThreadEvent&)
840 wxMessageOutputDebug().Printf("MYFRAME: MyThread update...\n");
843 void MyFrame::DoPauseThread()
845 // anytime we access the m_pThread pointer we must ensure that it won't
846 // be modified in the meanwhile; since only a single thread may be
847 // inside a given critical section at a given time, the following code
849 wxCriticalSectionLocker enter(m_pThreadCS);
851 if (m_pThread) // does the thread still exist?
853 // without a critical section, once reached this point it may happen
854 // that the OS scheduler gives control to the MyThread::Entry() function,
855 // which in turn may return (because it completes its work) making
856 // invalid the m_pThread pointer
858 if (m_pThread->Pause() != wxTHREAD_NO_ERROR )
859 wxLogError("Can't pause the thread!");
863 void MyFrame::OnClose(wxCloseEvent&)
866 wxCriticalSectionLocker enter(m_pThreadCS);
868 if (m_pThread) // does the thread still exist?
870 wxMessageOutputDebug().Printf("MYFRAME: deleting thread");
872 if (m_pThread->Delete() != wxTHREAD_NO_ERROR )
873 wxLogError("Can't delete the thread!");
875 } // exit from the critical section to give the thread
876 // the possibility to enter its destructor
877 // (which is guarded with m_pThreadCS critical section!)
881 { // was the ~MyThread() function executed?
882 wxCriticalSectionLocker enter(m_pThreadCS);
883 if (!m_pThread) break;
886 // wait for thread completion
887 wxThread::This()->Sleep(1);
894 For a more detailed and comprehensive example, see @sample{thread}.
895 For a simpler way to share data and synchronization objects between
896 the main and the secondary thread see wxThreadHelper.
898 Conversely, @b joinable threads do not delete themselves when they are done
899 processing and as such are safe to create on the stack. Joinable threads
900 also provide the ability for one to get value it returned from Entry()
902 You shouldn't hurry to create all the threads joinable, however, because this
903 has a disadvantage as well: you @b must Wait() for a joinable thread or the
904 system resources used by it will never be freed, and you also must delete the
905 corresponding wxThread object yourself if you did not create it on the stack.
906 In contrast, detached threads are of the "fire-and-forget" kind: you only have
907 to start a detached thread and it will terminate and destroy itself.
910 @section thread_deletion wxThread Deletion
912 Regardless of whether it has terminated or not, you should call Wait() on a
913 @b joinable thread to release its memory, as outlined in @ref thread_types.
914 If you created a joinable thread on the heap, remember to delete it manually
915 with the @c delete operator or similar means as only detached threads handle
916 this type of memory management.
918 Since @b detached threads delete themselves when they are finished processing,
919 you should take care when calling a routine on one. If you are certain the
920 thread is still running and would like to end it, you may call Delete()
921 to gracefully end it (which implies that the thread will be deleted after
922 that call to Delete()). It should be implied that you should @b never attempt
923 to delete a detached thread with the @c delete operator or similar means.
925 As mentioned, Wait() or Delete() functions attempt to gracefully terminate a
926 joinable and a detached thread, respectively. They do this by waiting until
927 the thread in question calls TestDestroy() or ends processing (i.e. returns
928 from wxThread::Entry).
930 Obviously, if the thread does call TestDestroy() and does not end, the
931 thread which called Wait() or Delete() will come to halt.
932 This is why it's important to call TestDestroy() in the Entry() routine of
933 your threads as often as possible and immediately exit when it returns @true.
935 As a last resort you can end the thread immediately through Kill(). It is
936 strongly recommended that you do not do this, however, as it does not free
937 the resources associated with the object (although the wxThread object of
938 detached threads will still be deleted) and could leave the C runtime
939 library in an undefined state.
942 @section thread_secondary wxWidgets Calls in Secondary Threads
944 All threads other than the "main application thread" (the one running
945 wxApp::OnInit() or the one your main function runs in, for example) are
946 considered "secondary threads". These include all threads created by Create()
947 or the corresponding constructors.
949 GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe
950 at all in secondary threads and could end your application prematurely.
951 This is due to several reasons, including the underlying native API and
952 the fact that wxThread does not run a GUI event loop similar to other APIs
955 A workaround for some wxWidgets ports is calling wxMutexGUIEnter()
956 before any GUI calls and then calling wxMutexGUILeave() afterwords.
957 However, the recommended way is to simply process the GUI calls in the main
958 thread through an event that is posted by wxQueueEvent().
959 This does not imply that calls to these classes are thread-safe, however,
960 as most wxWidgets classes are not thread-safe, including wxString.
963 @section thread_poll Don't Poll a wxThread
965 A common problem users experience with wxThread is that in their main thread
966 they will check the thread every now and then to see if it has ended through
967 IsRunning(), only to find that their application has run into problems
968 because the thread is using the default behaviour (i.e. it's @b detached) and
969 has already deleted itself.
970 Naturally, they instead attempt to use joinable threads in place of the previous
971 behaviour. However, polling a wxThread for when it has ended is in general a
972 bad idea - in fact calling a routine on any running wxThread should be avoided
973 if possible. Instead, find a way to notify yourself when the thread has ended.
975 Usually you only need to notify the main thread, in which case you can
976 post an event to it via wxQueueEvent().
977 In the case of secondary threads you can call a routine of another class
978 when the thread is about to complete processing and/or set the value of
979 a variable, possibly using mutexes (see wxMutex) and/or other synchronization
985 @see wxThreadHelper, wxMutex, wxCondition, wxCriticalSection,
992 The return type for the thread functions.
994 typedef void* ExitCode
;
997 This constructor creates a new detached (default) or joinable C++
998 thread object. It does not create or start execution of the real thread -
999 for this you should use the Create() and Run() methods.
1001 The possible values for @a kind parameters are:
1002 - @b wxTHREAD_DETACHED - Creates a detached thread.
1003 - @b wxTHREAD_JOINABLE - Creates a joinable thread.
1005 wxThread(wxThreadKind kind
= wxTHREAD_DETACHED
);
1008 The destructor frees the resources associated with the thread.
1009 Notice that you should never delete a detached thread -- you may only call
1010 Delete() on it or wait until it terminates (and auto destructs) itself.
1012 Because the detached threads delete themselves, they can only be allocated on the heap.
1013 Joinable threads should be deleted explicitly. The Delete() and Kill() functions
1014 will not delete the C++ thread object. It is also safe to allocate them on stack.
1016 virtual ~wxThread();
1019 Creates a new thread.
1021 The thread object is created in the suspended state, and you should call Run()
1022 to start running it. You may optionally specify the stack size to be allocated
1023 to it (Ignored on platforms that don't support setting it explicitly,
1024 eg. Unix system without @c pthread_attr_setstacksize).
1026 If you do not specify the stack size,the system's default value is used.
1029 It is a good idea to explicitly specify a value as systems'
1030 default values vary from just a couple of KB on some systems (BSD and
1031 OS/2 systems) to one or several MB (Windows, Solaris, Linux).
1032 So, if you have a thread that requires more than just a few KB of memory, you
1033 will have mysterious problems on some platforms but not on the common ones.
1034 On the other hand, just indicating a large stack size by default will give you
1035 performance issues on those systems with small default stack since those
1036 typically use fully committed memory for the stack.
1037 On the contrary, if you use a lot of threads (say several hundred),
1038 virtual address space can get tight unless you explicitly specify a
1039 smaller amount of thread stack space for each thread.
1042 - @b wxTHREAD_NO_ERROR - No error.
1043 - @b wxTHREAD_NO_RESOURCE - There were insufficient resources to create the thread.
1044 - @b wxTHREAD_NO_RUNNING - The thread is already running
1046 wxThreadError
Create(unsigned int stackSize
= 0);
1049 Calling Delete() gracefully terminates a @b detached thread, either when
1050 the thread calls TestDestroy() or when it finishes processing.
1053 The thread exit code, if rc is not NULL.
1056 As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
1057 should be used as the wait mode even although currently
1058 wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
1059 new in wxWidgets 2.9.2.
1062 This function works on a joinable thread but in that case makes
1063 the TestDestroy() function of the thread return @true and then
1064 waits for its completion (i.e. it differs from Wait() because
1065 it asks the thread to terminate before waiting).
1067 See @ref thread_deletion for a broader explanation of this routine.
1069 wxThreadError
Delete(ExitCode
*rc
= NULL
,
1070 wxThreadWait waitMode
= wxTHREAD_WAIT_BLOCK
);
1073 Returns the number of system CPUs or -1 if the value is unknown.
1075 For multi-core systems the returned value is typically the total number
1076 of @e cores, since the OS usually abstract a single N-core CPU
1077 as N different cores.
1079 @see SetConcurrency()
1081 static int GetCPUCount();
1084 Returns the platform specific thread ID of the current thread as a long.
1086 This can be used to uniquely identify threads, even if they are not wxThreads.
1090 static wxThreadIdType
GetCurrentId();
1093 Gets the thread identifier: this is a platform dependent number that uniquely
1094 identifies the thread throughout the system during its existence
1095 (i.e. the thread identifiers may be reused).
1097 wxThreadIdType
GetId() const;
1100 Returns the thread kind as it was given in the ctor.
1104 wxThreadKind
GetKind() const;
1107 Returns the thread ID of the main thread.
1113 static wxThreadIdType
GetMainId();
1116 Gets the priority of the thread, between zero and 100.
1118 The following priorities are defined:
1119 - @b WXTHREAD_MIN_PRIORITY: 0
1120 - @b WXTHREAD_DEFAULT_PRIORITY: 50
1121 - @b WXTHREAD_MAX_PRIORITY: 100
1123 unsigned int GetPriority() const;
1126 Returns @true if the thread is alive (i.e. started and not terminating).
1128 Note that this function can only safely be used with joinable threads, not
1129 detached ones as the latter delete themselves and so when the real thread is
1130 no longer alive, it is not possible to call this function because
1131 the wxThread object no longer exists.
1133 bool IsAlive() const;
1136 Returns @true if the thread is of the detached kind, @false if it is a
1139 bool IsDetached() const;
1142 Returns @true if the calling thread is the main application thread.
1144 Main thread in the context of wxWidgets is the one which initialized
1147 @see GetMainId(), GetCurrentId()
1149 static bool IsMain();
1152 Returns @true if the thread is paused.
1154 bool IsPaused() const;
1157 Returns @true if the thread is running.
1159 This method may only be safely used for joinable threads, see the remark in
1162 bool IsRunning() const;
1165 Immediately terminates the target thread.
1167 @b "This function is dangerous and should be used with extreme care"
1168 (and not used at all whenever possible)! The resources allocated to the
1169 thread will not be freed and the state of the C runtime library may become
1170 inconsistent. Use Delete() for detached threads or Wait() for joinable
1173 For detached threads Kill() will also delete the associated C++ object.
1174 However this will not happen for joinable threads and this means that you will
1175 still have to delete the wxThread object yourself to avoid memory leaks.
1177 In neither case OnExit() of the dying thread will be called, so no
1178 thread-specific cleanup will be performed.
1179 This function can only be called from another thread context, i.e. a thread
1182 It is also an error to call this function for a thread which is not running or
1183 paused (in the latter case, the thread will be resumed first) -- if you do it,
1184 a @b wxTHREAD_NOT_RUNNING error will be returned.
1186 wxThreadError
Kill();
1189 Suspends the thread.
1191 Under some implementations (Win32), the thread is suspended immediately,
1192 under others it will only be suspended when it calls TestDestroy() for
1193 the next time (hence, if the thread doesn't call it at all, it won't be
1196 This function can only be called from another thread context.
1198 wxThreadError
Pause();
1201 Resumes a thread suspended by the call to Pause().
1203 This function can only be called from another thread context.
1205 wxThreadError
Resume();
1208 Starts the thread execution. Should be called after Create().
1210 Note that once you Run() a @b detached thread, @e any function call you do
1211 on the thread pointer (you must allocate it on the heap) is @e "unsafe";
1212 i.e. the thread may have terminated at any moment after Run() and your pointer
1213 may be dangling. See @ref thread_types for an example of safe manipulation
1214 of detached threads.
1216 This function can only be called from another thread context.
1218 Finally, note that once a thread has completed and its Entry() function
1219 returns, you cannot call Run() on it again (an assert will fail in debug
1220 builds or @c wxTHREAD_RUNNING will be returned in release builds).
1222 wxThreadError
Run();
1225 Sets the thread concurrency level for this process.
1227 This is, roughly, the number of threads that the system tries to schedule
1229 The value of 0 for @a level may be used to set the default one.
1231 @return @true on success or @false otherwise (for example, if this function is
1232 not implemented for this platform -- currently everything except Solaris).
1234 static bool SetConcurrency(size_t level
);
1237 Sets the priority of the thread, between 0 and 100.
1238 It can only be set after calling Create() but before calling Run().
1240 The following priorities are defined:
1241 - @b WXTHREAD_MIN_PRIORITY: 0
1242 - @b WXTHREAD_DEFAULT_PRIORITY: 50
1243 - @b WXTHREAD_MAX_PRIORITY: 100
1245 void SetPriority(unsigned int priority
);
1248 Pauses the thread execution for the given amount of time.
1250 This is the same as wxMilliSleep().
1252 static void Sleep(unsigned long milliseconds
);
1255 This function should be called periodically by the thread to ensure that
1256 calls to Pause() and Delete() will work.
1258 If it returns @true, the thread should exit as soon as possible.
1259 Notice that under some platforms (POSIX), implementation of Pause() also
1260 relies on this function being called, so not calling it would prevent
1261 both stopping and suspending thread from working.
1263 virtual bool TestDestroy();
1266 Return the thread object for the calling thread.
1268 @NULL is returned if the calling thread is the main (GUI) thread, but
1269 IsMain() should be used to test whether the thread is really the main one
1270 because @NULL may also be returned for the thread not created with wxThread
1271 class. Generally speaking, the return value for such a thread is undefined.
1273 static wxThread
* This();
1276 Waits for a @b joinable thread to terminate and returns the value the thread
1277 returned from Entry() or @c "(ExitCode)-1" on error. Notice that, unlike
1278 Delete(), this function doesn't cancel the thread in any way so the caller
1279 waits for as long as it takes to the thread to exit.
1281 You can only Wait() for @b joinable (not detached) threads.
1283 This function can only be called from another thread context.
1286 As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
1287 should be used as the wait mode even although currently
1288 wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
1289 new in wxWidgets 2.9.2.
1291 See @ref thread_deletion for a broader explanation of this routine.
1293 ExitCode
Wait(wxThreadWait flags
= wxTHREAD_WAIT_BLOCK
);
1296 Give the rest of the thread's time-slice to the system allowing the other
1299 Note that using this function is @b strongly discouraged, since in
1300 many cases it indicates a design weakness of your threading model
1301 (as does using Sleep() functions).
1303 Threads should use the CPU in an efficient manner, i.e. they should
1304 do their current work efficiently, then as soon as the work is done block
1305 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
1306 get signalled e.g. by other threads or a user device once further thread
1308 Using Yield() or Sleep() indicates polling-type behaviour, since we're
1309 fuzzily giving up our timeslice and wait until sometime later we'll get
1310 reactivated, at which time we realize that there isn't really much to do
1311 and Yield() again...
1313 The most critical characteristic of Yield() is that it's operating system
1314 specific: there may be scheduler changes which cause your thread to not
1315 wake up relatively soon again, but instead many seconds later,
1316 causing huge performance issues for your application.
1319 With a well-behaving, CPU-efficient thread the operating system is likely
1320 to properly care for its reactivation the moment it needs it, whereas with
1321 non-deterministic, Yield-using threads all bets are off and the system
1322 scheduler is free to penalize them drastically</strong>, and this effect
1323 gets worse with increasing system load due to less free CPU resources available.
1324 You may refer to various Linux kernel @c sched_yield discussions for more
1329 static void Yield();
1334 This is the entry point of the thread.
1336 This function is pure virtual and must be implemented by any derived class.
1337 The thread execution will start here.
1339 The returned value is the thread exit code which is only useful for
1340 joinable threads and is the value returned by Wait().
1341 This function is called by wxWidgets itself and should never be called
1344 virtual ExitCode
Entry() = 0;
1347 This is a protected function of the wxThread class and thus can only be called
1348 from a derived class. It also can only be called in the context of this
1349 thread, i.e. a thread can only exit from itself, not from another thread.
1351 This function will terminate the OS thread (i.e. stop the associated path of
1352 execution) and also delete the associated C++ object for detached threads.
1353 OnExit() will be called just before exiting.
1355 void Exit(ExitCode exitcode
= 0);
1360 Called when the thread exits.
1362 This function is called in the context of the thread associated with the
1363 wxThread object, not in the context of the main thread.
1364 This function will not be called if the thread was @ref Kill() killed.
1366 This function should never be called directly.
1368 virtual void OnExit();
1372 /** See wxSemaphore. */
1375 wxSEMA_NO_ERROR
= 0,
1376 wxSEMA_INVALID
, //!< semaphore hasn't been initialized successfully
1377 wxSEMA_BUSY
, //!< returned by TryWait() if Wait() would block
1378 wxSEMA_TIMEOUT
, //!< returned by WaitTimeout()
1379 wxSEMA_OVERFLOW
, //!< Post() would increase counter past the max
1386 wxSemaphore is a counter limiting the number of threads concurrently accessing
1387 a shared resource. This counter is always between 0 and the maximum value
1388 specified during the semaphore creation. When the counter is strictly greater
1389 than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
1390 counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
1391 block and only return when the semaphore counter becomes strictly positive
1392 again as the result of calling wxSemaphore::Post which increments the counter.
1394 In general, semaphores are useful to restrict access to a shared resource
1395 which can only be accessed by some fixed number of clients at the same time.
1396 For example, when modeling a hotel reservation system a semaphore with the counter
1397 equal to the total number of available rooms could be created. Each time a room
1398 is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
1399 and each time a room is freed it should be released by calling wxSemaphore::Post.
1402 @category{threading}
1408 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
1409 there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
1410 mutex (but unlike a mutex it can be released by a thread different from the one
1413 @a initialcount is the initial value of the semaphore which must be between
1414 0 and @a maxcount (if it is not set to 0).
1416 wxSemaphore(int initialcount
= 0, int maxcount
= 0);
1419 Destructor is not virtual, don't use this class polymorphically.
1424 Increments the semaphore count and signals one of the waiting
1425 threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
1426 would increase the counter past the maximum.
1429 - wxSEMA_NO_ERROR: There was no error.
1430 - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
1431 - wxSEMA_OVERFLOW: Post() would increase counter past the max.
1432 - wxSEMA_MISC_ERROR: Miscellaneous error.
1437 Same as Wait(), but returns immediately.
1440 - wxSEMA_NO_ERROR: There was no error.
1441 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1442 - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
1443 - wxSEMA_MISC_ERROR: Miscellaneous error.
1445 wxSemaError
TryWait();
1448 Wait indefinitely until the semaphore count becomes strictly positive
1449 and then decrement it and return.
1452 - wxSEMA_NO_ERROR: There was no error.
1453 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1454 - wxSEMA_MISC_ERROR: Miscellaneous error.
1459 Same as Wait(), but with a timeout limit.
1462 - wxSEMA_NO_ERROR: There was no error.
1463 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1464 - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
1465 - wxSEMA_MISC_ERROR: Miscellaneous error.
1467 wxSemaError
WaitTimeout(unsigned long timeout_millis
);
1473 @class wxMutexLocker
1475 This is a small helper class to be used with wxMutex objects.
1477 A wxMutexLocker acquires a mutex lock in the constructor and releases
1478 (or unlocks) the mutex in the destructor making it much more difficult to
1479 forget to release a mutex (which, in general, will promptly lead to serious
1480 problems). See wxMutex for an example of wxMutexLocker usage.
1483 @category{threading}
1485 @see wxMutex, wxCriticalSectionLocker
1491 Constructs a wxMutexLocker object associated with mutex and locks it.
1492 Call IsOk() to check if the mutex was successfully locked.
1494 wxMutexLocker(wxMutex
& mutex
);
1497 Destructor releases the mutex if it was successfully acquired in the ctor.
1502 Returns @true if mutex was acquired in the constructor, @false otherwise.
1509 The possible wxMutex kinds.
1513 /** Normal non-recursive mutex: try to always use this one. */
1516 /** Recursive mutex: don't use these ones with wxCondition. */
1522 The possible wxMutex errors.
1526 /** The operation completed successfully. */
1527 wxMUTEX_NO_ERROR
= 0,
1529 /** The mutex hasn't been initialized. */
1532 /** The mutex is already locked by the calling thread. */
1535 /** The mutex is already locked by another thread. */
1538 /** An attempt to unlock a mutex which is not locked. */
1541 /** wxMutex::LockTimeout() has timed out. */
1544 /** Any other error */
1552 A mutex object is a synchronization object whose state is set to signaled when
1553 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
1554 from its usefulness in coordinating mutually-exclusive access to a shared
1555 resource as only one thread at a time can own a mutex object.
1557 Mutexes may be recursive in the sense that a thread can lock a mutex which it
1558 had already locked before (instead of dead locking the entire process in this
1559 situation by starting to wait on a mutex which will never be released while the
1560 thread is waiting) but using them is not recommended under Unix and they are
1561 @b not recursive by default. The reason for this is that recursive
1562 mutexes are not supported by all Unix flavours and, worse, they cannot be used
1565 For example, when several threads use the data stored in the linked list,
1566 modifications to the list should only be allowed to one thread at a time
1567 because during a new node addition the list integrity is temporarily broken
1568 (this is also called @e program @e invariant).
1571 // this variable has an "s_" prefix because it is static: seeing an "s_" in
1572 // a multithreaded program is in general a good sign that you should use a
1573 // mutex (or a critical section)
1574 static wxMutex *s_mutexProtectingTheGlobalData;
1576 // we store some numbers in this global array which is presumably used by
1577 // several threads simultaneously
1580 void MyThread::AddNewNode(int num)
1582 // ensure that no other thread accesses the list
1583 s_mutexProtectingTheGlobalList->Lock();
1587 s_mutexProtectingTheGlobalList->Unlock();
1590 // return true if the given number is greater than all array elements
1591 bool MyThread::IsGreater(int num)
1593 // before using the list we must acquire the mutex
1594 wxMutexLocker lock(s_mutexProtectingTheGlobalData);
1596 size_t count = s_data.Count();
1597 for ( size_t n = 0; n < count; n++ )
1599 if ( s_data[n] > num )
1607 Notice how wxMutexLocker was used in the second function to ensure that the
1608 mutex is unlocked in any case: whether the function returns true or false
1609 (because the destructor of the local object @e lock is always called).
1610 Using this class instead of directly using wxMutex is, in general, safer
1611 and is even more so if your program uses C++ exceptions.
1614 @category{threading}
1616 @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
1622 Default constructor.
1624 wxMutex(wxMutexType type
= wxMUTEX_DEFAULT
);
1627 Destroys the wxMutex object.
1632 Locks the mutex object.
1633 This is equivalent to LockTimeout() with infinite timeout.
1635 Note that if this mutex is already locked by the caller thread,
1636 this function doesn't block but rather immediately returns.
1638 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
1640 wxMutexError
Lock();
1643 Try to lock the mutex object during the specified time interval.
1645 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
1647 wxMutexError
LockTimeout(unsigned long msec
);
1650 Tries to lock the mutex object. If it can't, returns immediately with an error.
1652 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
1654 wxMutexError
TryLock();
1657 Unlocks the mutex object.
1659 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
1661 wxMutexError
Unlock();
1666 // ============================================================================
1667 // Global functions/macros
1668 // ============================================================================
1670 /** @addtogroup group_funcmacro_thread */
1674 This macro declares a (static) critical section object named @a cs if
1675 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1677 @header{wx/thread.h}
1679 #define wxCRIT_SECT_DECLARE(cs)
1682 This macro declares a critical section object named @a cs if
1683 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
1684 the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
1685 declare a class or struct member which explains its name.
1687 @header{wx/thread.h}
1689 #define wxCRIT_SECT_DECLARE_MEMBER(cs)
1692 This macro creates a wxCriticalSectionLocker named @a name and associated
1693 with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
1696 @header{wx/thread.h}
1698 #define wxCRIT_SECT_LOCKER(name, cs)
1701 This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
1702 creates a static critical section object and also the lock object
1703 associated with it. Because of this, it can be only used inside a function,
1704 not at global scope. For example:
1709 static int s_counter = 0;
1711 wxCRITICAL_SECTION(counter);
1717 Note that this example assumes that the function is called the first time
1718 from the main thread so that the critical section object is initialized
1719 correctly by the time other threads start calling it, if this is not the
1720 case this approach can @b not be used and the critical section must be made
1723 @header{wx/thread.h}
1725 #define wxCRITICAL_SECTION(name)
1728 This macro is equivalent to
1729 @ref wxCriticalSection::Leave "critical_section.Leave()" if
1730 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1732 @header{wx/thread.h}
1734 #define wxLEAVE_CRIT_SECT(critical_section)
1737 This macro is equivalent to
1738 @ref wxCriticalSection::Enter "critical_section.Enter()" if
1739 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1741 @header{wx/thread.h}
1743 #define wxENTER_CRIT_SECT(critical_section)
1746 Returns @true if this thread is the main one. Always returns @true if
1747 @c wxUSE_THREADS is 0.
1749 @header{wx/thread.h}
1751 bool wxIsMainThread();
1756 This function must be called when any thread other than the main GUI thread
1757 wants to get access to the GUI library. This function will block the
1758 execution of the calling thread until the main thread (or any other thread
1759 holding the main GUI lock) leaves the GUI library and no other thread will
1760 enter the GUI library until the calling thread calls wxMutexGuiLeave().
1762 Typically, these functions are used like this:
1765 void MyThread::Foo(void)
1767 // before doing any GUI calls we must ensure that
1768 // this thread is the only one doing it!
1773 my_window->DrawSomething();
1779 This function is only defined on platforms which support preemptive
1780 threads and only works under some ports (wxMSW currently).
1782 @note Under GTK, no creation of top-level windows is allowed in any thread
1785 @header{wx/thread.h}
1787 void wxMutexGuiEnter();
1790 This function is only defined on platforms which support preemptive
1793 @see wxMutexGuiEnter()
1795 @header{wx/thread.h}
1797 void wxMutexGuiLeave();