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