1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of all thread-related wxWidgets classes
4 // Author: wxWidgets team
6 // Licence: wxWindows license
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
);
191 // There are 2 types of mutexes: normal mutexes and recursive ones. The attempt
192 // to lock a normal mutex by a thread which already owns it results in
193 // undefined behaviour (it always works under Windows, it will almost always
194 // result in a deadlock under Unix). Locking a recursive mutex in such
195 // situation always succeeds and it must be unlocked as many times as it has
198 // However recursive mutexes have several important drawbacks: first, in the
199 // POSIX implementation, they're less efficient. Second, and more importantly,
200 // they CAN NOT BE USED WITH CONDITION VARIABLES under Unix! Using them with
201 // wxCondition will work under Windows and some Unices (notably Linux) but will
202 // deadlock under other Unix versions (e.g. Solaris). As it might be difficult
203 // to ensure that a recursive mutex is not used with wxCondition, it is a good
204 // idea to avoid using recursive mutexes at all. Also, the last problem with
205 // them is that some (older) Unix versions don't support this at all -- which
206 // results in a configure warning when building and a deadlock when using them.
210 @class wxCriticalSectionLocker
212 This is a small helper class to be used with wxCriticalSection objects.
214 A wxCriticalSectionLocker enters the critical section in the constructor and
215 leaves it in the destructor making it much more difficult to forget to leave
216 a critical section (which, in general, will lead to serious and difficult
224 // gs_critSect is some (global) critical section guarding access to the
226 wxCriticalSectionLocker locker(gs_critSect);
243 Without wxCriticalSectionLocker, you would need to remember to manually leave
244 the critical section before each @c return.
249 @see wxCriticalSection, wxMutexLocker
251 class wxCriticalSectionLocker
255 Constructs a wxCriticalSectionLocker object associated with given
256 @a criticalsection and enters it.
258 wxCriticalSectionLocker(wxCriticalSection
& criticalsection
);
261 Destructor leaves the critical section.
263 ~wxCriticalSectionLocker();
269 @class wxThreadHelper
271 The wxThreadHelper class is a mix-in class that manages a single background
272 thread. By deriving from wxThreadHelper, a class can implement the thread
273 code in its own wxThreadHelper::Entry() method and easily share data and
274 synchronization objects between the main thread and the worker thread.
276 Doing this prevents the awkward passing of pointers that is needed when the
277 original object in the main thread needs to synchronize with its worker thread
278 in its own wxThread derived object.
280 For example, wxFrame may need to make some calculations in a background thread
281 and then display the results of those calculations in the main window.
283 Ordinarily, a wxThread derived object would be created with the calculation
284 code implemented in wxThread::Entry. To access the inputs to the calculation,
285 the frame object would often to pass a pointer to itself to the thread object.
286 Similarly, the frame object would hold a pointer to the thread object.
287 Shared data and synchronization objects could be stored in either object
288 though the object without the data would have to access the data through
290 However, with wxThreadHelper, the frame object and the thread object are
291 treated as the same object. Shared data and synchronization variables are
292 stored in the single object, eliminating a layer of indirection and the
304 This constructor simply initializes a member variable.
309 The destructor frees the resources associated with the thread.
311 virtual ~wxThreadHelper();
314 This is the entry point of the thread.
316 This function is pure virtual and must be implemented by any derived class.
317 The thread execution will start here.
319 The returned value is the thread exit code which is only useful for
320 joinable threads and is the value returned by @c "GetThread()->Wait()".
322 This function is called by wxWidgets itself and should never be called
325 virtual ExitCode
Entry() = 0;
328 Creates a new thread.
330 The thread object is created in the suspended state, and you
331 should call @ref wxThread::Run GetThread()-Run to start running it.
333 You may optionally specify the stack size to be allocated to it (ignored
334 on platforms that don't support setting it explicitly, eg. Unix).
336 @return One of the ::wxThreadError enum values.
338 wxThreadError
Create(unsigned int stackSize
= 0);
341 This is a public function that returns the wxThread object
342 associated with the thread.
344 wxThread
* GetThread() const;
348 Possible critical section types
351 enum wxCriticalSectionType
354 /** Recursive critical section under both Windows and Unix */
356 wxCRITSEC_NON_RECURSIVE
357 /** Non-recursive critical section under Unix, recursive under Windows */
361 @class wxCriticalSection
363 A critical section object is used for exactly the same purpose as a wxMutex.
364 The only difference is that under Windows platform critical sections are only
365 visible inside one process, while mutexes may be shared among processes,
366 so using critical sections is slightly more efficient.
368 The terminology is also slightly different: mutex may be locked (or acquired)
369 and unlocked (or released) while critical section is entered and left by the program.
371 Finally, you should try to use wxCriticalSectionLocker class whenever
372 possible instead of directly using wxCriticalSection for the same reasons
373 wxMutexLocker is preferrable to wxMutex - please see wxMutex for an example.
378 @see wxThread, wxCondition, wxCriticalSectionLocker
380 class wxCriticalSection
384 Default constructor initializes critical section object.
385 By default critical sections are recursive under Unix and Windows.
387 wxCriticalSection( wxCriticalSectionType critSecType
= wxCRITSEC_DEFAULT
);
390 Destructor frees the resources.
392 ~wxCriticalSection();
395 Enter the critical section (same as locking a mutex).
397 There is no error return for this function.
398 After entering the critical section protecting some global
399 data the thread running in critical section may safely use/modify it.
404 Leave the critical section allowing other threads use the global data
405 protected by it. There is no error return for this function.
411 The possible thread kinds.
415 /** Detached thread */
418 /** Joinable thread */
423 The possible thread errors.
428 wxTHREAD_NO_ERROR
= 0,
430 /** No resource left to create a new thread. */
431 wxTHREAD_NO_RESOURCE
,
433 /** The thread is already running. */
436 /** The thread isn't running. */
437 wxTHREAD_NOT_RUNNING
,
439 /** Thread we waited for had to be killed. */
442 /** Some other error */
447 Defines the interval of priority
451 WXTHREAD_MIN_PRIORITY
= 0u,
452 WXTHREAD_DEFAULT_PRIORITY
= 50u,
453 WXTHREAD_MAX_PRIORITY
= 100u
460 A thread is basically a path of execution through a program.
461 Threads are sometimes called @e light-weight processes, but the fundamental difference
462 between threads and processes is that memory spaces of different processes are
463 separated while all threads share the same address space.
465 While it makes it much easier to share common data between several threads, it
466 also makes it much easier to shoot oneself in the foot, so careful use of
467 synchronization objects such as mutexes() or critical sections (see wxCriticalSection)
468 is recommended. In addition, don't create global thread objects because they
469 allocate memory in their constructor, which will cause problems for the memory
472 @section thread_types Types of wxThreads
474 There are two types of threads in wxWidgets: @e detached and @e joinable,
475 modeled after the the POSIX thread API. This is different from the Win32 API
476 where all threads are joinable.
478 By default wxThreads in wxWidgets use the detached behavior. Detached threads
479 delete themselves once they have completed, either by themselves when they
480 complete processing or through a call to Delete(), and thus
481 must be created on the heap (through the new operator, for example).
482 Conversely, joinable threads do not delete themselves when they are done
483 processing and as such are safe to create on the stack. Joinable threads
484 also provide the ability for one to get value it returned from Entry()
487 You shouldn't hurry to create all the threads joinable, however, because this
488 has a disadvantage as well: you @b must Wait() for a joinable thread or the
489 system resources used by it will never be freed, and you also must delete the
490 corresponding wxThread object yourself if you did not create it on the stack.
491 In contrast, detached threads are of the "fire-and-forget" kind: you only have to
492 start a detached thread and it will terminate and destroy itself.
495 @section thread_deletion wxThread Deletion
497 Regardless of whether it has terminated or not, you should call Wait() on a
498 joinable thread to release its memory, as outlined in @ref thread_types.
499 If you created a joinable thread on the heap, remember to delete it manually
500 with the @c delete operator or similar means as only detached threads handle
501 this type of memory management.
503 Since detached threads delete themselves when they are finished processing,
504 you should take care when calling a routine on one. If you are certain the
505 thread is still running and would like to end it, you may call Delete()
506 to gracefully end it (which implies that the thread will be deleted after
507 that call to Delete()). It should be implied that you should never attempt
508 to delete a detached thread with the delete operator or similar means.
509 As mentioned, Wait() or Delete() attempts to gracefully terminate a
510 joinable and detached thread, respectively. It does this by waiting until
511 the thread in question calls TestDestroy() or ends processing (returns
512 from wxThread::Entry).
514 Obviously, if the thread does call TestDestroy() and does not end the calling
515 thread will come to halt. This is why it is important to call TestDestroy() in
516 the Entry() routine of your threads as often as possible.
517 As a last resort you can end the thread immediately through Kill(). It is
518 strongly recommended that you do not do this, however, as it does not free
519 the resources associated with the object (although the wxThread object of
520 detached threads will still be deleted) and could leave the C runtime
521 library in an undefined state.
524 @section thread_secondary wxWidgets Calls in Secondary Threads
526 All threads other than the "main application thread" (the one
527 wxApp::OnInit() or your main function runs in, for example) are considered
528 "secondary threads". These include all threads created by Create() or the
529 corresponding constructors.
531 GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe
532 at all in secondary threads and could end your application prematurely.
533 This is due to several reasons, including the underlying native API and
534 the fact that wxThread does not run a GUI event loop similar to other APIs
537 A workaround for some wxWidgets ports is calling wxMutexGUIEnter()
538 before any GUI calls and then calling wxMutexGUILeave() afterwords. However,
539 the recommended way is to simply process the GUI calls in the main thread
540 through an event that is posted by either wxQueueEvent().
541 This does not imply that calls to these classes are thread-safe, however,
542 as most wxWidgets classes are not thread-safe, including wxString.
545 @section thread_poll Don't Poll a wxThread
547 A common problem users experience with wxThread is that in their main thread
548 they will check the thread every now and then to see if it has ended through
549 IsRunning(), only to find that their application has run into problems
550 because the thread is using the default behavior and has already deleted
551 itself. Naturally, they instead attempt to use joinable threads in place
552 of the previous behavior. However, polling a wxThread for when it has ended
553 is in general a bad idea - in fact calling a routine on any running wxThread
554 should be avoided if possible. Instead, find a way to notify yourself when
555 the thread has ended.
557 Usually you only need to notify the main thread, in which case you can
558 post an event to it via wxPostEvent() or wxEvtHandler::AddPendingEvent().
559 In the case of secondary threads you can call a routine of another class
560 when the thread is about to complete processing and/or set the value of
561 a variable, possibly using mutexes (see wxMutex) and/or other synchronization
567 @see wxMutex, wxCondition, wxCriticalSection
573 This constructor creates a new detached (default) or joinable C++
574 thread object. It does not create or start execution of the real thread -
575 for this you should use the Create() and Run() methods.
577 The possible values for @a kind parameters are:
578 - @b wxTHREAD_DETACHED - Creates a detached thread.
579 - @b wxTHREAD_JOINABLE - Creates a joinable thread.
581 wxThread(wxThreadKind kind
= wxTHREAD_DETACHED
);
584 The destructor frees the resources associated with the thread.
585 Notice that you should never delete a detached thread -- you may only call
586 Delete() on it or wait until it terminates (and auto destructs) itself.
588 Because the detached threads delete themselves, they can only be allocated on the heap.
589 Joinable threads should be deleted explicitly. The Delete() and Kill() functions
590 will not delete the C++ thread object. It is also safe to allocate them on stack.
595 Creates a new thread.
597 The thread object is created in the suspended state, and you should call Run()
598 to start running it. You may optionally specify the stack size to be allocated
599 to it (Ignored on platforms that don't support setting it explicitly,
600 eg. Unix system without @c pthread_attr_setstacksize).
602 If you do not specify the stack size,the system's default value is used.
605 It is a good idea to explicitly specify a value as systems'
606 default values vary from just a couple of KB on some systems (BSD and
607 OS/2 systems) to one or several MB (Windows, Solaris, Linux).
608 So, if you have a thread that requires more than just a few KB of memory, you
609 will have mysterious problems on some platforms but not on the common ones.
610 On the other hand, just indicating a large stack size by default will give you
611 performance issues on those systems with small default stack since those
612 typically use fully committed memory for the stack.
613 On the contrary, if you use a lot of threads (say several hundred),
614 virtual adress space can get tight unless you explicitly specify a
615 smaller amount of thread stack space for each thread.
618 - @b wxTHREAD_NO_ERROR - No error.
619 - @b wxTHREAD_NO_RESOURCE - There were insufficient resources to create the thread.
620 - @b wxTHREAD_NO_RUNNING - The thread is already running
622 wxThreadError
Create(unsigned int stackSize
= 0);
625 Calling Delete() gracefully terminates a detached thread, either when
626 the thread calls TestDestroy() or finished processing.
629 While this could work on a joinable thread you simply should not
630 call this routine on one as afterwards you may not be able to call
631 Wait() to free the memory of that thread).
633 See @ref thread_deletion for a broader explanation of this routine.
635 wxThreadError
Delete(void** rc
= NULL
);
638 Returns the number of system CPUs or -1 if the value is unknown.
640 @see SetConcurrency()
642 static int GetCPUCount();
645 Returns the platform specific thread ID of the current thread as a long.
646 This can be used to uniquely identify threads, even if they are not wxThreads.
648 static unsigned long GetCurrentId();
651 Gets the thread identifier: this is a platform dependent number that uniquely
652 identifies the thread throughout the system during its existence
653 (i.e. the thread identifiers may be reused).
655 wxThreadIdType
GetId() const;
658 Gets the priority of the thread, between zero and 100.
660 The following priorities are defined:
661 - @b WXTHREAD_MIN_PRIORITY: 0
662 - @b WXTHREAD_DEFAULT_PRIORITY: 50
663 - @b WXTHREAD_MAX_PRIORITY: 100
665 unsigned int GetPriority() const;
668 Returns @true if the thread is alive (i.e. started and not terminating).
670 Note that this function can only safely be used with joinable threads, not
671 detached ones as the latter delete themselves and so when the real thread is
672 no longer alive, it is not possible to call this function because
673 the wxThread object no longer exists.
675 bool IsAlive() const;
678 Returns @true if the thread is of the detached kind, @false if it is a
681 bool IsDetached() const;
684 Returns @true if the calling thread is the main application thread.
686 static bool IsMain();
689 Returns @true if the thread is paused.
691 bool IsPaused() const;
694 Returns @true if the thread is running.
696 This method may only be safely used for joinable threads, see the remark in
699 bool IsRunning() const;
702 Immediately terminates the target thread.
704 @b "This function is dangerous and should be used with extreme care"
705 (and not used at all whenever possible)! The resources allocated to the
706 thread will not be freed and the state of the C runtime library may become
707 inconsistent. Use Delete() for detached threads or Wait() for joinable
710 For detached threads Kill() will also delete the associated C++ object.
711 However this will not happen for joinable threads and this means that you will
712 still have to delete the wxThread object yourself to avoid memory leaks.
714 In neither case OnExit() of the dying thread will be called, so no
715 thread-specific cleanup will be performed.
716 This function can only be called from another thread context, i.e. a thread
719 It is also an error to call this function for a thread which is not running or
720 paused (in the latter case, the thread will be resumed first) -- if you do it,
721 a @b wxTHREAD_NOT_RUNNING error will be returned.
723 wxThreadError
Kill();
726 Called when the thread exits.
728 This function is called in the context of the thread associated with the
729 wxThread object, not in the context of the main thread.
730 This function will not be called if the thread was @ref Kill() killed.
732 This function should never be called directly.
734 virtual void OnExit();
739 Under some implementations (Win32), the thread is suspended immediately,
740 under others it will only be suspended when it calls TestDestroy() for
741 the next time (hence, if the thread doesn't call it at all, it won't be
744 This function can only be called from another thread context.
746 wxThreadError
Pause();
749 Resumes a thread suspended by the call to Pause().
751 This function can only be called from another thread context.
753 wxThreadError
Resume();
756 Starts the thread execution. Should be called after
759 This function can only be called from another thread context.
764 Sets the thread concurrency level for this process.
766 This is, roughly, the number of threads that the system tries to schedule
768 The value of 0 for @a level may be used to set the default one.
770 @return @true on success or @false otherwise (for example, if this function is
771 not implemented for this platform -- currently everything except Solaris).
773 static bool SetConcurrency(size_t level
);
776 Sets the priority of the thread, between 0 and 100.
777 It can only be set after calling Create() but before calling Run().
779 The following priorities are defined:
780 - @b WXTHREAD_MIN_PRIORITY: 0
781 - @b WXTHREAD_DEFAULT_PRIORITY: 50
782 - @b WXTHREAD_MAX_PRIORITY: 100
784 void SetPriority(unsigned int priority
);
787 Pauses the thread execution for the given amount of time.
789 This is the same as wxMilliSleep().
791 static void Sleep(unsigned long milliseconds
);
794 This function should be called periodically by the thread to ensure that
795 calls to Pause() and Delete() will work.
797 If it returns @true, the thread should exit as soon as possible.
798 Notice that under some platforms (POSIX), implementation of Pause() also
799 relies on this function being called, so not calling it would prevent
800 both stopping and suspending thread from working.
802 virtual bool TestDestroy();
805 Return the thread object for the calling thread.
807 @NULL is returned if the calling thread is the main (GUI) thread, but
808 IsMain() should be used to test whether the thread is really the main one
809 because @NULL may also be returned for the thread not created with wxThread
810 class. Generally speaking, the return value for such a thread is undefined.
812 static wxThread
* This();
815 Waits for a joinable thread to terminate and returns the value the thread
816 returned from Entry() or @c (ExitCode)-1 on error. Notice that, unlike
817 Delete() doesn't cancel the thread in any way so the caller waits for as
818 long as it takes to the thread to exit.
820 You can only Wait() for joinable (not detached) threads.
821 This function can only be called from another thread context.
823 See @ref thread_deletion for a broader explanation of this routine.
828 Give the rest of the thread time slice to the system allowing the other
831 Note that using this function is @b strongly discouraged, since in
832 many cases it indicates a design weakness of your threading model
833 (as does using Sleep() functions).
835 Threads should use the CPU in an efficient manner, i.e. they should
836 do their current work efficiently, then as soon as the work is done block
837 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
838 get signalled e.g. by other threads or a user device once further thread
840 Using Yield() or Sleep() indicates polling-type behaviour, since we're
841 fuzzily giving up our timeslice and wait until sometime later we'll get
842 reactivated, at which time we realize that there isn't really much to do
845 The most critical characteristic of Yield() is that it's operating system
846 specific: there may be scheduler changes which cause your thread to not
847 wake up relatively soon again, but instead many seconds later,
848 causing huge performance issues for your application.
851 With a well-behaving, CPU-efficient thread the operating system is likely
852 to properly care for its reactivation the moment it needs it, whereas with
853 non-deterministic, Yield-using threads all bets are off and the system
854 scheduler is free to penalize drastically</strong>, and this effect gets worse
855 with increasing system load due to less free CPU resources available.
856 You may refer to various Linux kernel @c sched_yield discussions for more
866 This is the entry point of the thread.
868 This function is pure virtual and must be implemented by any derived class.
869 The thread execution will start here.
871 The returned value is the thread exit code which is only useful for
872 joinable threads and is the value returned by Wait().
873 This function is called by wxWidgets itself and should never be called
876 virtual ExitCode
Entry() = 0;
879 This is a protected function of the wxThread class and thus can only be called
880 from a derived class. It also can only be called in the context of this
881 thread, i.e. a thread can only exit from itself, not from another thread.
883 This function will terminate the OS thread (i.e. stop the associated path of
884 execution) and also delete the associated C++ object for detached threads.
885 OnExit() will be called just before exiting.
887 void Exit(ExitCode exitcode
= 0);
891 /** See wxSemaphore. */
895 wxSEMA_INVALID
, //!< semaphore hasn't been initialized successfully
896 wxSEMA_BUSY
, //!< returned by TryWait() if Wait() would block
897 wxSEMA_TIMEOUT
, //!< returned by WaitTimeout()
898 wxSEMA_OVERFLOW
, //!< Post() would increase counter past the max
905 wxSemaphore is a counter limiting the number of threads concurrently accessing
906 a shared resource. This counter is always between 0 and the maximum value
907 specified during the semaphore creation. When the counter is strictly greater
908 than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
909 counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
910 block and only return when the semaphore counter becomes strictly positive
911 again as the result of calling wxSemaphore::Post which increments the counter.
913 In general, semaphores are useful to restrict access to a shared resource
914 which can only be accessed by some fixed number of clients at the same time.
915 For example, when modeling a hotel reservation system a semaphore with the counter
916 equal to the total number of available rooms could be created. Each time a room
917 is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
918 and each time a room is freed it should be released by calling wxSemaphore::Post.
927 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
928 there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
929 mutex (but unlike a mutex it can be released by a thread different from the one
932 @a initialcount is the initial value of the semaphore which must be between
933 0 and @a maxcount (if it is not set to 0).
935 wxSemaphore(int initialcount
= 0, int maxcount
= 0);
938 Destructor is not virtual, don't use this class polymorphically.
943 Increments the semaphore count and signals one of the waiting
944 threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
945 would increase the counter past the maximum.
948 - wxSEMA_NO_ERROR: There was no error.
949 - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
950 - wxSEMA_OVERFLOW: Post() would increase counter past the max.
951 - wxSEMA_MISC_ERROR: Miscellaneous error.
956 Same as Wait(), but returns immediately.
959 - wxSEMA_NO_ERROR: There was no error.
960 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
961 - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
962 - wxSEMA_MISC_ERROR: Miscellaneous error.
964 wxSemaError
TryWait();
967 Wait indefinitely until the semaphore count becomes strictly positive
968 and then decrement it and return.
971 - wxSEMA_NO_ERROR: There was no error.
972 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
973 - wxSEMA_MISC_ERROR: Miscellaneous error.
978 Same as Wait(), but with a timeout limit.
981 - wxSEMA_NO_ERROR: There was no error.
982 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
983 - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
984 - wxSEMA_MISC_ERROR: Miscellaneous error.
986 wxSemaError
WaitTimeout(unsigned long timeout_millis
);
994 This is a small helper class to be used with wxMutex objects.
996 A wxMutexLocker acquires a mutex lock in the constructor and releases
997 (or unlocks) the mutex in the destructor making it much more difficult to
998 forget to release a mutex (which, in general, will promptly lead to serious
999 problems). See wxMutex for an example of wxMutexLocker usage.
1002 @category{threading}
1004 @see wxMutex, wxCriticalSectionLocker
1010 Constructs a wxMutexLocker object associated with mutex and locks it.
1011 Call IsOk() to check if the mutex was successfully locked.
1013 wxMutexLocker(wxMutex
& mutex
);
1016 Destructor releases the mutex if it was successfully acquired in the ctor.
1021 Returns @true if mutex was acquired in the constructor, @false otherwise.
1028 The possible wxMutex kinds.
1032 /** Normal non-recursive mutex: try to always use this one. */
1035 /** Recursive mutex: don't use these ones with wxCondition. */
1041 The possible wxMutex errors.
1045 /** The operation completed successfully. */
1046 wxMUTEX_NO_ERROR
= 0,
1048 /** The mutex hasn't been initialized. */
1051 /** The mutex is already locked by the calling thread. */
1054 /** The mutex is already locked by another thread. */
1057 /** An attempt to unlock a mutex which is not locked. */
1060 /** wxMutex::LockTimeout() has timed out. */
1063 /** Any other error */
1071 A mutex object is a synchronization object whose state is set to signaled when
1072 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
1073 from its usefulness in coordinating mutually-exclusive access to a shared
1074 resource as only one thread at a time can own a mutex object.
1076 Mutexes may be recursive in the sense that a thread can lock a mutex which it
1077 had already locked before (instead of dead locking the entire process in this
1078 situation by starting to wait on a mutex which will never be released while the
1079 thread is waiting) but using them is not recommended under Unix and they are
1080 @b not recursive by default. The reason for this is that recursive
1081 mutexes are not supported by all Unix flavours and, worse, they cannot be used
1084 For example, when several threads use the data stored in the linked list,
1085 modifications to the list should only be allowed to one thread at a time
1086 because during a new node addition the list integrity is temporarily broken
1087 (this is also called @e program invariant).
1090 // this variable has an "s_" prefix because it is static: seeing an "s_" in
1091 // a multithreaded program is in general a good sign that you should use a
1092 // mutex (or a critical section)
1093 static wxMutex *s_mutexProtectingTheGlobalData;
1095 // we store some numbers in this global array which is presumably used by
1096 // several threads simultaneously
1099 void MyThread::AddNewNode(int num)
1101 // ensure that no other thread accesses the list
1102 s_mutexProtectingTheGlobalList->Lock();
1106 s_mutexProtectingTheGlobalList->Unlock();
1109 // return true if the given number is greater than all array elements
1110 bool MyThread::IsGreater(int num)
1112 // before using the list we must acquire the mutex
1113 wxMutexLocker lock(s_mutexProtectingTheGlobalData);
1115 size_t count = s_data.Count();
1116 for ( size_t n = 0; n < count; n++ )
1118 if ( s_data[n] > num )
1126 Notice how wxMutexLocker was used in the second function to ensure that the
1127 mutex is unlocked in any case: whether the function returns true or false
1128 (because the destructor of the local object lock is always called). Using
1129 this class instead of directly using wxMutex is, in general safer and is
1130 even more so if your program uses C++ exceptions.
1133 @category{threading}
1135 @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
1141 Default constructor.
1143 wxMutex(wxMutexType type
= wxMUTEX_DEFAULT
);
1146 Destroys the wxMutex object.
1151 Locks the mutex object.
1152 This is equivalent to LockTimeout() with infinite timeout.
1154 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
1156 wxMutexError
Lock();
1159 Try to lock the mutex object during the specified time interval.
1161 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
1163 wxMutexError
LockTimeout(unsigned long msec
);
1166 Tries to lock the mutex object. If it can't, returns immediately with an error.
1168 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
1170 wxMutexError
TryLock();
1173 Unlocks the mutex object.
1175 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
1177 wxMutexError
Unlock();
1182 // ============================================================================
1183 // Global functions/macros
1184 // ============================================================================
1186 /** @ingroup group_funcmacro_thread */
1190 This macro declares a (static) critical section object named @a cs if
1191 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1193 @header{wx/thread.h}
1195 #define wxCRIT_SECT_DECLARE(cs)
1198 This macro declares a critical section object named @a cs if
1199 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
1200 the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
1201 declare a class or struct member which explains its name.
1203 @header{wx/thread.h}
1205 #define wxCRIT_SECT_DECLARE_MEMBER(cs)
1208 This macro creates a wxCriticalSectionLocker named @a name and associated
1209 with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
1212 @header{wx/thread.h}
1214 #define wxCRIT_SECT_LOCKER(name, cs)
1217 This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
1218 creates a static critical section object and also the lock object
1219 associated with it. Because of this, it can be only used inside a function,
1220 not at global scope. For example:
1225 static int s_counter = 0;
1227 wxCRITICAL_SECTION(counter);
1233 Note that this example assumes that the function is called the first time
1234 from the main thread so that the critical section object is initialized
1235 correctly by the time other threads start calling it, if this is not the
1236 case this approach can @b not be used and the critical section must be made
1239 @header{wx/thread.h}
1241 #define wxCRITICAL_SECTION(name)
1244 This macro is equivalent to
1245 @ref wxCriticalSection::Leave "critical_section.Leave()" if
1246 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1248 @header{wx/thread.h}
1250 #define wxLEAVE_CRIT_SECT(critical_section)
1253 This macro is equivalent to
1254 @ref wxCriticalSection::Enter "critical_section.Enter()" if
1255 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1257 @header{wx/thread.h}
1259 #define wxENTER_CRIT_SECT(critical_section)
1262 Returns @true if this thread is the main one. Always returns @true if
1263 @c wxUSE_THREADS is 0.
1265 @header{wx/thread.h}
1267 bool wxIsMainThread();
1270 This function must be called when any thread other than the main GUI thread
1271 wants to get access to the GUI library. This function will block the
1272 execution of the calling thread until the main thread (or any other thread
1273 holding the main GUI lock) leaves the GUI library and no other thread will
1274 enter the GUI library until the calling thread calls wxMutexGuiLeave().
1276 Typically, these functions are used like this:
1279 void MyThread::Foo(void)
1281 // before doing any GUI calls we must ensure that
1282 // this thread is the only one doing it!
1287 my_window-DrawSomething();
1293 This function is only defined on platforms which support preemptive
1296 @note Under GTK, no creation of top-level windows is allowed in any thread
1299 @header{wx/thread.h}
1301 void wxMutexGuiEnter();
1304 This function is only defined on platforms which support preemptive
1307 @see wxMutexGuiEnter()
1309 @header{wx/thread.h}
1311 void wxMutexGuiLeave();