]> git.saurik.com Git - wxWidgets.git/blob - interface/thread.h
fixed category
[wxWidgets.git] / interface / thread.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: thread.h
3 // Purpose: documentation for wxCondition class
4 // Author: wxWidgets team
5 // RCS-ID: $Id$
6 // Licence: wxWindows license
7 /////////////////////////////////////////////////////////////////////////////
8
9 /**
10 @class wxCondition
11 @wxheader{thread.h}
12
13 wxCondition variables correspond to pthread conditions or to Win32 event
14 objects. They may be used in a multithreaded application to wait until the
15 given condition becomes @true which happens when the condition becomes signaled.
16
17 For example, if a worker thread is doing some long task and another thread has
18 to wait until it is finished, the latter thread will wait on the condition
19 object and the worker thread will signal it on exit (this example is not
20 perfect because in this particular case it would be much better to just
21 wxThread::Wait for the worker thread, but if there are several
22 worker threads it already makes much more sense).
23
24 Note that a call to wxCondition::Signal may happen before the
25 other thread calls wxCondition::Wait and, just as with the
26 pthread conditions, the signal is then lost and so if you want to be sure that
27 you don't miss it you must keep the mutex associated with the condition
28 initially locked and lock it again before calling
29 wxCondition::Signal. Of course, this means that this call is
30 going to block until wxCondition::Wait is called by another
31 thread.
32
33 @library{wxbase}
34 @category{thread}
35
36 @seealso
37 wxThread, wxMutex
38 */
39 class wxCondition
40 {
41 public:
42 /**
43 Default and only constructor. The @a mutex must be locked by the caller
44 before calling Wait() function.
45 Use IsOk() to check if the object was successfully
46 initialized.
47 */
48 wxCondition(wxMutex& mutex);
49
50 /**
51 Destroys the wxCondition object. The destructor is not virtual so this class
52 should not be used polymorphically.
53 */
54 ~wxCondition();
55
56 /**
57 Broadcasts to all waiting threads, waking all of them up. Note that this method
58 may be called whether the mutex associated with this condition is locked or
59 not.
60
61 @see Signal()
62 */
63 void Broadcast();
64
65 /**
66 Returns @true if the object had been initialized successfully, @false
67 if an error occurred.
68 */
69 bool IsOk() const;
70
71 /**
72 Signals the object waking up at most one thread. If several threads are waiting
73 on the same condition, the exact thread which is woken up is undefined. If no
74 threads are waiting, the signal is lost and the condition would have to be
75 signalled again to wake up any thread which may start waiting on it later.
76 Note that this method may be called whether the mutex associated with this
77 condition is locked or not.
78
79 @see Broadcast()
80 */
81 void Signal();
82
83 /**
84 Waits until the condition is signalled.
85 This method atomically releases the lock on the mutex associated with this
86 condition (this is why it must be locked prior to calling Wait) and puts the
87 thread to sleep until Signal() or
88 Broadcast() is called. It then locks the mutex
89 again and returns.
90 Note that even if Signal() had been called before
91 Wait without waking up any thread, the thread would still wait for another one
92 and so it is important to ensure that the condition will be signalled after
93 Wait or the thread may sleep forever.
94
95 @returns Returns wxCOND_NO_ERROR on success, another value if an error
96 occurred.
97
98 @see WaitTimeout()
99 */
100 wxCondError Wait();
101
102 /**
103 Waits until the condition is signalled or the timeout has elapsed.
104 This method is identical to Wait() except that it
105 returns, with the return code of @c wxCOND_TIMEOUT as soon as the given
106 timeout expires.
107
108 @param milliseconds
109 Timeout in milliseconds
110 */
111 wxCondError WaitTimeout(unsigned long milliseconds);
112 };
113
114
115 /**
116 @class wxCriticalSectionLocker
117 @wxheader{thread.h}
118
119 This is a small helper class to be used with wxCriticalSection
120 objects. A wxCriticalSectionLocker enters the critical section in the
121 constructor and leaves it in the destructor making it much more difficult to
122 forget to leave a critical section (which, in general, will lead to serious
123 and difficult to debug problems).
124
125 Example of using it:
126
127 @code
128 void Set Foo()
129 {
130 // gs_critSect is some (global) critical section guarding access to the
131 // object "foo"
132 wxCriticalSectionLocker locker(gs_critSect);
133
134 if ( ... )
135 {
136 // do something
137 ...
138
139 return;
140 }
141
142 // do something else
143 ...
144
145 return;
146 }
147 @endcode
148
149 Without wxCriticalSectionLocker, you would need to remember to manually leave
150 the critical section before each @c return.
151
152 @library{wxbase}
153 @category{thread}
154
155 @seealso
156 wxCriticalSection, wxMutexLocker
157 */
158 class wxCriticalSectionLocker
159 {
160 public:
161 /**
162 Constructs a wxCriticalSectionLocker object associated with given
163 @a criticalsection and enters it.
164 */
165 wxCriticalSectionLocker(wxCriticalSection& criticalsection);
166
167 /**
168 Destructor leaves the critical section.
169 */
170 ~wxCriticalSectionLocker();
171 };
172
173
174 /**
175 @class wxThreadHelper
176 @wxheader{thread.h}
177
178 The wxThreadHelper class is a mix-in class that manages a single background
179 thread. By deriving from wxThreadHelper, a class can implement the thread
180 code in its own wxThreadHelper::Entry method
181 and easily share data and synchronization objects between the main thread
182 and the worker thread. Doing this prevents the awkward passing of pointers
183 that is needed when the original object in the main thread needs to
184 synchronize with its worker thread in its own wxThread derived object.
185
186 For example, wxFrame may need to make some calculations
187 in a background thread and then display the results of those calculations in
188 the main window.
189
190 Ordinarily, a wxThread derived object would be created
191 with the calculation code implemented in
192 wxThread::Entry. To access the inputs to the
193 calculation, the frame object would often to pass a pointer to itself to the
194 thread object. Similarly, the frame object would hold a pointer to the
195 thread object. Shared data and synchronization objects could be stored in
196 either object though the object without the data would have to access the
197 data through a pointer.
198
199 However, with wxThreadHelper, the frame object and the thread object are
200 treated as the same object. Shared data and synchronization variables are
201 stored in the single object, eliminating a layer of indirection and the
202 associated pointers.
203
204 @library{wxbase}
205 @category{thread}
206
207 @seealso
208 wxThread
209 */
210 class wxThreadHelper
211 {
212 public:
213 /**
214 This constructor simply initializes a member variable.
215 */
216 wxThreadHelper();
217
218 /**
219 The destructor frees the resources associated with the thread.
220 */
221 ~wxThreadHelper();
222
223 /**
224 Creates a new thread. The thread object is created in the suspended state, and
225 you
226 should call @ref wxThread::run GetThread()-Run to start running
227 it. You may optionally specify the stack size to be allocated to it (Ignored on
228 platforms that don't support setting it explicitly, eg. Unix).
229
230 @returns One of:
231 */
232 wxThreadError Create(unsigned int stackSize = 0);
233
234 /**
235 This is the entry point of the thread. This function is pure virtual and must
236 be implemented by any derived class. The thread execution will start here.
237 The returned value is the thread exit code which is only useful for
238 joinable threads and is the value returned by
239 @ref wxThread::wait GetThread()-Wait.
240 This function is called by wxWidgets itself and should never be called
241 directly.
242 */
243 virtual ExitCode Entry();
244
245 /**
246 This is a public function that returns the wxThread object
247 associated with the thread.
248 */
249 wxThread* GetThread();
250
251 /**
252 wxThread * m_thread
253 the actual wxThread object.
254 */
255 };
256
257
258 /**
259 @class wxCriticalSection
260 @wxheader{thread.h}
261
262 A critical section object is used for exactly the same purpose as
263 mutexes. The only difference is that under Windows platform
264 critical sections are only visible inside one process, while mutexes may be
265 shared between processes, so using critical sections is slightly more
266 efficient. The terminology is also slightly different: mutex may be locked (or
267 acquired) and unlocked (or released) while critical section is entered and left
268 by the program.
269
270 Finally, you should try to use
271 wxCriticalSectionLocker class whenever
272 possible instead of directly using wxCriticalSection for the same reasons
273 wxMutexLocker is preferrable to
274 wxMutex - please see wxMutex for an example.
275
276 @library{wxbase}
277 @category{thread}
278
279 @seealso
280 wxThread, wxCondition, wxCriticalSectionLocker
281 */
282 class wxCriticalSection
283 {
284 public:
285 /**
286 Default constructor initializes critical section object.
287 */
288 wxCriticalSection();
289
290 /**
291 Destructor frees the resources.
292 */
293 ~wxCriticalSection();
294
295 /**
296 Enter the critical section (same as locking a mutex). There is no error return
297 for this function. After entering the critical section protecting some global
298 data the thread running in critical section may safely use/modify it.
299 */
300 void Enter();
301
302 /**
303 Leave the critical section allowing other threads use the global data protected
304 by it. There is no error return for this function.
305 */
306 void Leave();
307 };
308
309
310 /**
311 @class wxThread
312 @wxheader{thread.h}
313
314 A thread is basically a path of execution through a program. Threads are
315 sometimes called @e light-weight processes, but the fundamental difference
316 between threads and processes is that memory spaces of different processes are
317 separated while all threads share the same address space.
318
319 While it makes it much easier to share common data between several threads, it
320 also
321 makes it much easier to shoot oneself in the foot, so careful use of
322 synchronization
323 objects such as mutexes or @ref overview_wxcriticalsection "critical sections"
324 is recommended. In addition, don't create global thread
325 objects because they allocate memory in their constructor, which will cause
326 problems for the memory checking system.
327
328 @library{wxbase}
329 @category{thread}
330
331 @seealso
332 wxMutex, wxCondition, wxCriticalSection
333 */
334 class wxThread
335 {
336 public:
337 /**
338 This constructor creates a new detached (default) or joinable C++ thread
339 object. It
340 does not create or start execution of the real thread -- for this you should
341 use the Create() and Run() methods.
342 The possible values for @a kind parameters are:
343
344 @b wxTHREAD_DETACHED
345
346 Creates a detached thread.
347
348 @b wxTHREAD_JOINABLE
349
350 Creates a joinable thread.
351 */
352 wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
353
354 /**
355 The destructor frees the resources associated with the thread. Notice that you
356 should never delete a detached thread -- you may only call
357 Delete() on it or wait until it terminates (and auto
358 destructs) itself. Because the detached threads delete themselves, they can
359 only be allocated on the heap.
360 Joinable threads should be deleted explicitly. The Delete() and Kill() functions
361 will not delete the C++ thread object. It is also safe to allocate them on
362 stack.
363 */
364 ~wxThread();
365
366 /**
367 Creates a new thread. The thread object is created in the suspended state, and
368 you
369 should call Run() to start running it. You may optionally
370 specify the stack size to be allocated to it (Ignored on platforms that don't
371 support setting it explicitly, eg. Unix system without
372 @c pthread_attr_setstacksize). If you do not specify the stack size,
373 the system's default value is used.
374 @b Warning: It is a good idea to explicitly specify a value as systems'
375 default values vary from just a couple of KB on some systems (BSD and
376 OS/2 systems) to one or several MB (Windows, Solaris, Linux). So, if you
377 have a thread that requires more than just a few KB of memory, you will
378 have mysterious problems on some platforms but not on the common ones. On the
379 other hand, just indicating a large stack size by default will give you
380 performance issues on those systems with small default stack since those
381 typically use fully committed memory for the stack. On the contrary, if
382 use a lot of threads (say several hundred), virtual adress space can get tight
383 unless you explicitly specify a smaller amount of thread stack space for each
384 thread.
385
386 @returns One of:
387 */
388 wxThreadError Create(unsigned int stackSize = 0);
389
390 /**
391 Calling Delete() gracefully terminates a
392 detached thread, either when the thread calls TestDestroy() or finished
393 processing.
394 (Note that while this could work on a joinable thread you simply should not
395 call this routine on one as afterwards you may not be able to call
396 Wait() to free the memory of that thread).
397 See @ref overview_deletionwxthread "wxThread deletion" for a broader
398 explanation of this routine.
399 */
400 wxThreadError Delete();
401
402 /**
403 A common problem users experience with wxThread is that in their main thread
404 they will check the thread every now and then to see if it has ended through
405 IsRunning(), only to find that their
406 application has run into problems because the thread is using the default
407 behavior and has already deleted itself. Naturally, they instead attempt to
408 use joinable threads in place of the previous behavior.
409 However, polling a wxThread for when it has ended is in general a bad idea -
410 in fact calling a routine on any running wxThread should be avoided if
411 possible. Instead, find a way to notify yourself when the thread has ended.
412 Usually you only need to notify the main thread, in which case you can post
413 an event to it via wxPostEvent or
414 wxEvtHandler::AddPendingEvent. In
415 the case of secondary threads you can call a routine of another class
416 when the thread is about to complete processing and/or set the value
417 of a variable, possibly using mutexes and/or other
418 synchronization means if necessary.
419 */
420
421
422 /**
423 This is the entry point of the thread. This function is pure virtual and must
424 be implemented by any derived class. The thread execution will start here.
425 The returned value is the thread exit code which is only useful for
426 joinable threads and is the value returned by Wait().
427 This function is called by wxWidgets itself and should never be called
428 directly.
429 */
430 virtual ExitCode Entry();
431
432 /**
433 This is a protected function of the wxThread class and thus can only be called
434 from a derived class. It also can only be called in the context of this
435 thread, i.e. a thread can only exit from itself, not from another thread.
436 This function will terminate the OS thread (i.e. stop the associated path of
437 execution) and also delete the associated C++ object for detached threads.
438 OnExit() will be called just before exiting.
439 */
440 void Exit(ExitCode exitcode = 0);
441
442 /**
443 Returns the number of system CPUs or -1 if the value is unknown.
444
445 @see SetConcurrency()
446 */
447 static int GetCPUCount();
448
449 /**
450 Returns the platform specific thread ID of the current thread as a
451 long. This can be used to uniquely identify threads, even if they are
452 not wxThreads.
453 */
454 static unsigned long GetCurrentId();
455
456 /**
457 Gets the thread identifier: this is a platform dependent number that uniquely
458 identifies the
459 thread throughout the system during its existence (i.e. the thread identifiers
460 may be reused).
461 */
462 unsigned long GetId() const;
463
464 /**
465 Gets the priority of the thread, between zero and 100.
466 The following priorities are defined:
467
468 @b WXTHREAD_MIN_PRIORITY
469
470 0
471
472 @b WXTHREAD_DEFAULT_PRIORITY
473
474 50
475
476 @b WXTHREAD_MAX_PRIORITY
477
478 100
479 */
480 int GetPriority() const;
481
482 /**
483 Returns @true if the thread is alive (i.e. started and not terminating).
484 Note that this function can only safely be used with joinable threads, not
485 detached ones as the latter delete themselves and so when the real thread is
486 no longer alive, it is not possible to call this function because
487 the wxThread object no longer exists.
488 */
489 bool IsAlive() const;
490
491 /**
492 Returns @true if the thread is of the detached kind, @false if it is a
493 joinable
494 one.
495 */
496 bool IsDetached() const;
497
498 /**
499 Returns @true if the calling thread is the main application thread.
500 */
501 static bool IsMain();
502
503 /**
504 Returns @true if the thread is paused.
505 */
506 bool IsPaused() const;
507
508 /**
509 Returns @true if the thread is running.
510 This method may only be safely used for joinable threads, see the remark in
511 IsAlive().
512 */
513 bool IsRunning() const;
514
515 /**
516 Immediately terminates the target thread. @b This function is dangerous and
517 should
518 be used with extreme care (and not used at all whenever possible)! The resources
519 allocated to the thread will not be freed and the state of the C runtime library
520 may become inconsistent. Use Delete() for detached
521 threads or Wait() for joinable threads instead.
522 For detached threads Kill() will also delete the associated C++ object.
523 However this will not happen for joinable threads and this means that you will
524 still have to delete the wxThread object yourself to avoid memory leaks.
525 In neither case OnExit() of the dying thread will be
526 called, so no thread-specific cleanup will be performed.
527 This function can only be called from another thread context, i.e. a thread
528 cannot kill itself.
529 It is also an error to call this function for a thread which is not running or
530 paused (in the latter case, the thread will be resumed first) -- if you do it,
531 a @c wxTHREAD_NOT_RUNNING error will be returned.
532 */
533 wxThreadError Kill();
534
535 /**
536 Called when the thread exits. This function is called in the context of the
537 thread associated with the wxThread object, not in the context of the main
538 thread. This function will not be called if the thread was
539 @ref kill() killed.
540 This function should never be called directly.
541 */
542 void OnExit();
543
544 /**
545 Suspends the thread. Under some implementations (Win32), the thread is
546 suspended immediately, under others it will only be suspended when it calls
547 TestDestroy() for the next time (hence, if the
548 thread doesn't call it at all, it won't be suspended).
549 This function can only be called from another thread context.
550 */
551 wxThreadError Pause();
552
553 /**
554 Resumes a thread suspended by the call to Pause().
555 This function can only be called from another thread context.
556 */
557 wxThreadError Resume();
558
559 /**
560 Starts the thread execution. Should be called after
561 Create().
562 This function can only be called from another thread context.
563 */
564 wxThreadError Run();
565
566 /**
567 Sets the thread concurrency level for this process. This is, roughly, the
568 number of threads that the system tries to schedule to run in parallel.
569 The value of 0 for @a level may be used to set the default one.
570 Returns @true on success or @false otherwise (for example, if this function is
571 not implemented for this platform -- currently everything except Solaris).
572 */
573 static bool SetConcurrency(size_t level);
574
575 /**
576 Sets the priority of the thread, between 0 and 100. It can only be set
577 after calling Create() but before calling
578 Run().
579 The following priorities are already defined:
580
581 @b WXTHREAD_MIN_PRIORITY
582
583 0
584
585 @b WXTHREAD_DEFAULT_PRIORITY
586
587 50
588
589 @b WXTHREAD_MAX_PRIORITY
590
591 100
592 */
593 void SetPriority(int priority);
594
595 /**
596 Pauses the thread execution for the given amount of time.
597 This function should be used instead of wxSleep by all worker
598 threads (i.e. all except the main one).
599 */
600 static void Sleep(unsigned long milliseconds);
601
602 /**
603 This function should be called periodically by the thread to ensure that calls
604 to Pause() and Delete() will
605 work. If it returns @true, the thread should exit as soon as possible.
606 Notice that under some platforms (POSIX), implementation of
607 Pause() also relies on this function being called, so
608 not calling it would prevent both stopping and suspending thread from working.
609 */
610 virtual bool TestDestroy();
611
612 /**
613 Return the thread object for the calling thread. @NULL is returned if the
614 calling thread
615 is the main (GUI) thread, but IsMain() should be used to test
616 whether the thread is really the main one because @NULL may also be returned for
617 the thread
618 not created with wxThread class. Generally speaking, the return value for such
619 a thread
620 is undefined.
621 */
622 static wxThread* This();
623
624 /**
625 There are two types of threads in wxWidgets: @e detached and @e joinable,
626 modeled after the the POSIX thread API. This is different from the Win32 API
627 where all threads are joinable.
628 By default wxThreads in wxWidgets use the detached behavior. Detached threads
629 delete themselves once they have completed, either by themselves when they
630 complete
631 processing or through a call to Delete(), and thus
632 must be created on the heap (through the new operator, for example).
633 Conversely,
634 joinable threads do not delete themselves when they are done processing and as
635 such
636 are safe to create on the stack. Joinable threads also provide the ability
637 for one to get value it returned from Entry()
638 through Wait().
639 You shouldn't hurry to create all the threads joinable, however, because this
640 has a disadvantage as well: you @b must Wait() for a joinable thread or the
641 system resources used by it will never be freed, and you also must delete the
642 corresponding wxThread object yourself if you did not create it on the stack.
643 In
644 contrast, detached threads are of the "fire-and-forget" kind: you only have to
645 start
646 a detached thread and it will terminate and destroy itself.
647 */
648
649
650 /**
651 Waits for a joinable thread to terminate and returns the value the thread
652 returned from Entry() or @c (ExitCode)-1 on
653 error. Notice that, unlike Delete() doesn't cancel the
654 thread in any way so the caller waits for as long as it takes to the thread to
655 exit.
656 You can only Wait() for joinable (not detached) threads.
657 This function can only be called from another thread context.
658 See @ref overview_deletionwxthread "wxThread deletion" for a broader
659 explanation of this routine.
660 */
661 ExitCode Wait() const;
662
663 /**
664 Give the rest of the thread time slice to the system allowing the other threads
665 to run.
666 Note that using this function is @b strongly discouraged, since in
667 many cases it indicates a design weakness of your threading model (as
668 does using Sleep functions).
669 Threads should use the CPU in an efficient manner, i.e. they should
670 do their current work efficiently, then as soon as the work is done block
671 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...)
672 which will get signalled e.g. by other threads or a user device once further
673 thread work is available. Using Yield or Sleep
674 indicates polling-type behaviour, since we're fuzzily giving up our timeslice
675 and wait until sometime later we'll get reactivated, at which time we
676 realize that there isn't really much to do and Yield again...
677 The most critical characteristic of Yield is that it's operating system
678 specific: there may be scheduler changes which cause your thread to not
679 wake up relatively soon again, but instead many seconds later,
680 causing huge performance issues for your application. @b with a
681 well-behaving, CPU-efficient thread the operating system is likely to properly
682 care for its reactivation the moment it needs it, whereas with
683 non-deterministic, Yield-using threads all bets are off and the system
684 scheduler is free to penalize drastically, and this effect gets worse
685 with increasing system load due to less free CPU resources available.
686 You may refer to various Linux kernel sched_yield discussions for more
687 information.
688 See also Sleep().
689 */
690 void Yield();
691
692 /**
693 Regardless of whether it has terminated or not, you should call
694 Wait() on a joinable thread to release its
695 memory, as outlined in @ref overview_typeswxthread "Types of wxThreads". If you
696 created
697 a joinable thread on the heap, remember to delete it manually with the delete
698 operator or similar means as only detached threads handle this type of memory
699 management.
700 Since detached threads delete themselves when they are finished processing,
701 you should take care when calling a routine on one. If you are certain the
702 thread is still running and would like to end it, you may call
703 Delete() to gracefully end it (which implies
704 that the thread will be deleted after that call to Delete()). It should be
705 implied that you should never attempt to delete a detached thread with the
706 delete operator or similar means.
707 As mentioned, Wait() or
708 Delete() attempts to gracefully terminate
709 a joinable and detached thread, respectively. It does this by waiting until
710 the thread in question calls TestDestroy()
711 or ends processing (returns from wxThread::Entry).
712 Obviously, if the thread does call TestDestroy() and does not end the calling
713 thread will come to halt. This is why it is important to call TestDestroy() in
714 the Entry() routine of your threads as often as possible.
715 As a last resort you can end the thread immediately through
716 Kill(). It is strongly recommended that you
717 do not do this, however, as it does not free the resources associated with
718 the object (although the wxThread object of detached threads will still be
719 deleted) and could leave the C runtime library in an undefined state.
720 */
721
722
723 /**
724 All threads other then the "main application thread" (the one
725 wxApp::OnInit or your main function runs in, for
726 example) are considered "secondary threads". These include all threads created
727 by Create() or the corresponding constructors.
728 GUI calls, such as those to a wxWindow or
729 wxBitmap are explicitly not safe at all in secondary threads
730 and could end your application prematurely. This is due to several reasons,
731 including the underlying native API and the fact that wxThread does not run a
732 GUI event loop similar to other APIs as MFC.
733 A workaround that works on some wxWidgets ports is calling wxMutexGUIEnter
734 before any GUI calls and then calling wxMutexGUILeave afterwords. However,
735 the recommended way is to simply process the GUI calls in the main thread
736 through an event that is posted by either wxPostEvent or
737 wxEvtHandler::AddPendingEvent. This does
738 not imply that calls to these classes are thread-safe, however, as most
739 wxWidgets classes are not thread-safe, including wxString.
740 */
741 };
742
743
744 /**
745 @class wxSemaphore
746 @wxheader{thread.h}
747
748 wxSemaphore is a counter limiting the number of threads concurrently accessing
749 a shared resource. This counter is always between 0 and the maximum value
750 specified during the semaphore creation. When the counter is strictly greater
751 than 0, a call to wxSemaphore::Wait returns immediately and
752 decrements the counter. As soon as it reaches 0, any subsequent calls to
753 wxSemaphore::Wait block and only return when the semaphore
754 counter becomes strictly positive again as the result of calling
755 wxSemaphore::Post which increments the counter.
756
757 In general, semaphores are useful to restrict access to a shared resource
758 which can only be accessed by some fixed number of clients at the same time. For
759 example, when modeling a hotel reservation system a semaphore with the counter
760 equal to the total number of available rooms could be created. Each time a room
761 is reserved, the semaphore should be acquired by calling
762 wxSemaphore::Wait and each time a room is freed it should be
763 released by calling wxSemaphore::Post.
764
765 @library{wxbase}
766 @category{thread}
767 */
768 class wxSemaphore
769 {
770 public:
771 /**
772 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
773 there is no upper limit. If maxcount is 1, the semaphore behaves almost as a
774 mutex (but unlike a mutex it can be released by a thread different from the one
775 which acquired it).
776 @a initialcount is the initial value of the semaphore which must be between
777 0 and @a maxcount (if it is not set to 0).
778 */
779 wxSemaphore(int initialcount = 0, int maxcount = 0);
780
781 /**
782 Destructor is not virtual, don't use this class polymorphically.
783 */
784 ~wxSemaphore();
785
786 /**
787 Increments the semaphore count and signals one of the waiting
788 threads in an atomic way. Returns wxSEMA_OVERFLOW if the count
789 would increase the counter past the maximum.
790
791 @returns One of:
792 */
793 wxSemaError Post();
794
795 /**
796 Same as Wait(), but returns immediately.
797
798 @returns One of:
799 */
800 wxSemaError TryWait();
801
802 /**
803 Wait indefinitely until the semaphore count becomes strictly positive
804 and then decrement it and return.
805
806 @returns One of:
807 */
808 wxSemaError Wait();
809 };
810
811
812 /**
813 @class wxMutexLocker
814 @wxheader{thread.h}
815
816 This is a small helper class to be used with wxMutex
817 objects. A wxMutexLocker acquires a mutex lock in the constructor and releases
818 (or unlocks) the mutex in the destructor making it much more difficult to
819 forget to release a mutex (which, in general, will promptly lead to serious
820 problems). See wxMutex for an example of wxMutexLocker
821 usage.
822
823 @library{wxbase}
824 @category{thread}
825
826 @seealso
827 wxMutex, wxCriticalSectionLocker
828 */
829 class wxMutexLocker
830 {
831 public:
832 /**
833 Constructs a wxMutexLocker object associated with mutex and locks it.
834 Call @ref isok() IsLocked to check if the mutex was
835 successfully locked.
836 */
837 wxMutexLocker(wxMutex& mutex);
838
839 /**
840 Destructor releases the mutex if it was successfully acquired in the ctor.
841 */
842 ~wxMutexLocker();
843
844 /**
845 Returns @true if mutex was acquired in the constructor, @false otherwise.
846 */
847 bool IsOk() const;
848 };
849
850
851 /**
852 @class wxMutex
853 @wxheader{thread.h}
854
855 A mutex object is a synchronization object whose state is set to signaled when
856 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
857 from its usefulness in coordinating mutually-exclusive access to a shared
858 resource as only one thread at a time can own a mutex object.
859
860 Mutexes may be recursive in the sense that a thread can lock a mutex which it
861 had already locked before (instead of dead locking the entire process in this
862 situation by starting to wait on a mutex which will never be released while the
863 thread is waiting) but using them is not recommended under Unix and they are
864 @b not recursive there by default. The reason for this is that recursive
865 mutexes are not supported by all Unix flavours and, worse, they cannot be used
866 with wxCondition. On the other hand, Win32 mutexes are
867 always recursive.
868
869 For example, when several threads use the data stored in the linked list,
870 modifications to the list should only be allowed to one thread at a time
871 because during a new node addition the list integrity is temporarily broken
872 (this is also called @e program invariant).
873
874 @library{wxbase}
875 @category{thread}
876
877 @seealso
878 wxThread, wxCondition, wxMutexLocker, wxCriticalSection
879 */
880 class wxMutex
881 {
882 public:
883 /**
884 Default constructor.
885 */
886 wxMutex(wxMutexType type = wxMUTEX_DEFAULT);
887
888 /**
889 Destroys the wxMutex object.
890 */
891 ~wxMutex();
892
893 /**
894 Locks the mutex object. This is equivalent to
895 LockTimeout() with infinite timeout.
896
897 @returns One of:
898 */
899 wxMutexError Lock();
900
901 /**
902 Try to lock the mutex object during the specified time interval.
903
904 @returns One of:
905 */
906 wxMutexError LockTimeout(unsigned long msec);
907
908 /**
909 Tries to lock the mutex object. If it can't, returns immediately with an error.
910
911 @returns One of:
912 */
913 wxMutexError TryLock();
914
915 /**
916 Unlocks the mutex object.
917
918 @returns One of:
919 */
920 wxMutexError Unlock();
921 };
922
923
924 // ============================================================================
925 // Global functions/macros
926 // ============================================================================
927
928 /**
929 Returns @true if this thread is the main one. Always returns @true if
930 @c wxUSE_THREADS is 0.
931 */
932 bool wxIsMainThread();
933
934 /**
935 This macro combines wxCRIT_SECT_DECLARE and
936 wxCRIT_SECT_LOCKER: it creates a static critical
937 section object and also the lock object associated with it. Because of this, it
938 can be only used inside a function, not at global scope. For example:
939
940 @code
941 int IncCount()
942 {
943 static int s_counter = 0;
944
945 wxCRITICAL_SECTION(counter);
946
947 return ++s_counter;
948 }
949 @endcode
950
951 (note that we suppose that the function is called the first time from the main
952 thread so that the critical section object is initialized correctly by the time
953 other threads start calling it, if this is not the case this approach can
954 @b not be used and the critical section must be made a global instead).
955 */
956 #define wxCRITICAL_SECTION(name) /* implementation is private */
957
958 /**
959 This macro declares a critical section object named @a cs if
960 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't
961 include the @c static keyword (unlike
962 wxCRIT_SECT_DECLARE), it can be used to declare
963 a class or struct member which explains its name.
964 */
965 #define wxCRIT_SECT_DECLARE(cs) /* implementation is private */
966
967 /**
968 This function must be called when any thread other than the main GUI thread
969 wants to get access to the GUI library. This function will block the execution
970 of the calling thread until the main thread (or any other thread holding the
971 main GUI lock) leaves the GUI library and no other thread will enter the GUI
972 library until the calling thread calls ::wxMutexGuiLeave.
973 Typically, these functions are used like this:
974
975 @code
976 void MyThread::Foo(void)
977 {
978 // before doing any GUI calls we must ensure that this thread is the only
979 // one doing it!
980
981 wxMutexGuiEnter();
982
983 // Call GUI here:
984 my_window-DrawSomething();
985
986 wxMutexGuiLeave();
987 }
988 @endcode
989
990 Note that under GTK, no creation of top-level windows is allowed in any
991 thread but the main one.
992 This function is only defined on platforms which support preemptive
993 threads.
994 */
995 void wxMutexGuiEnter();
996
997 /**
998 This macro declares a (static) critical section object named @a cs if
999 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1000 */
1001 #define wxCRIT_SECT_DECLARE(cs) /* implementation is private */
1002
1003 /**
1004 This macro is equivalent to @ref wxCriticalSection::leave cs.Leave if
1005 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1006 */
1007 #define wxLEAVE_CRIT_SECT(wxCriticalSection& cs) /* implementation is private */
1008
1009 /**
1010 This macro creates a @ref overview_wxcriticalsectionlocker "critical section
1011 lock"
1012 object named @a name and associated with the critical section @a cs if
1013 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1014 */
1015 #define wxCRIT_SECT_LOCKER(name, cs) /* implementation is private */
1016
1017 /**
1018 This macro is equivalent to @ref wxCriticalSection::enter cs.Enter if
1019 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1020 */
1021 #define wxENTER_CRIT_SECT(wxCriticalSection& cs) /* implementation is private */
1022