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