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