other ifacecheck fixes
[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 wxCondError 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 wxCondError 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 This is the entry point of the thread.
315
316 This function is pure virtual and must be implemented by any derived class.
317 The thread execution will start here.
318
319 The returned value is the thread exit code which is only useful for
320 joinable threads and is the value returned by @c "GetThread()->Wait()".
321
322 This function is called by wxWidgets itself and should never be called
323 directly.
324 */
325 virtual ExitCode Entry();
326
327 /**
328 Creates a new thread.
329
330 The thread object is created in the suspended state, and you
331 should call @ref wxThread::Run GetThread()-Run to start running it.
332
333 You may optionally specify the stack size to be allocated to it (ignored
334 on platforms that don't support setting it explicitly, eg. Unix).
335
336 @return One of the ::wxThreadError enum values.
337 */
338 wxThreadError Create(unsigned int stackSize = 0);
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 Returns the number of system CPUs or -1 if the value is unknown.
639
640 @see SetConcurrency()
641 */
642 static int GetCPUCount();
643
644 /**
645 Returns the platform specific thread ID of the current thread as a long.
646 This can be used to uniquely identify threads, even if they are not wxThreads.
647 */
648 static unsigned long GetCurrentId();
649
650 /**
651 Gets the thread identifier: this is a platform dependent number that uniquely
652 identifies the thread throughout the system during its existence
653 (i.e. the thread identifiers may be reused).
654 */
655 unsigned long GetId() const;
656
657 /**
658 Gets the priority of the thread, between zero and 100.
659
660 The following priorities are defined:
661 - @b WXTHREAD_MIN_PRIORITY: 0
662 - @b WXTHREAD_DEFAULT_PRIORITY: 50
663 - @b WXTHREAD_MAX_PRIORITY: 100
664 */
665 int GetPriority() const;
666
667 /**
668 Returns @true if the thread is alive (i.e. started and not terminating).
669
670 Note that this function can only safely be used with joinable threads, not
671 detached ones as the latter delete themselves and so when the real thread is
672 no longer alive, it is not possible to call this function because
673 the wxThread object no longer exists.
674 */
675 bool IsAlive() const;
676
677 /**
678 Returns @true if the thread is of the detached kind, @false if it is a
679 joinable one.
680 */
681 bool IsDetached() const;
682
683 /**
684 Returns @true if the calling thread is the main application thread.
685 */
686 static bool IsMain();
687
688 /**
689 Returns @true if the thread is paused.
690 */
691 bool IsPaused() const;
692
693 /**
694 Returns @true if the thread is running.
695
696 This method may only be safely used for joinable threads, see the remark in
697 IsAlive().
698 */
699 bool IsRunning() const;
700
701 /**
702 Immediately terminates the target thread.
703
704 @b "This function is dangerous and should be used with extreme care"
705 (and not used at all whenever possible)! The resources allocated to the
706 thread will not be freed and the state of the C runtime library may become
707 inconsistent. Use Delete() for detached threads or Wait() for joinable
708 threads instead.
709
710 For detached threads Kill() will also delete the associated C++ object.
711 However this will not happen for joinable threads and this means that you will
712 still have to delete the wxThread object yourself to avoid memory leaks.
713
714 In neither case OnExit() of the dying thread will be called, so no
715 thread-specific cleanup will be performed.
716 This function can only be called from another thread context, i.e. a thread
717 cannot kill itself.
718
719 It is also an error to call this function for a thread which is not running or
720 paused (in the latter case, the thread will be resumed first) -- if you do it,
721 a @b wxTHREAD_NOT_RUNNING error will be returned.
722 */
723 wxThreadError Kill();
724
725 /**
726 Called when the thread exits.
727
728 This function is called in the context of the thread associated with the
729 wxThread object, not in the context of the main thread.
730 This function will not be called if the thread was @ref Kill() killed.
731
732 This function should never be called directly.
733 */
734 virtual void OnExit();
735
736 /**
737 Suspends the thread.
738
739 Under some implementations (Win32), the thread is suspended immediately,
740 under others it will only be suspended when it calls TestDestroy() for
741 the next time (hence, if the thread doesn't call it at all, it won't be
742 suspended).
743
744 This function can only be called from another thread context.
745 */
746 wxThreadError Pause();
747
748 /**
749 Resumes a thread suspended by the call to Pause().
750
751 This function can only be called from another thread context.
752 */
753 wxThreadError Resume();
754
755 /**
756 Starts the thread execution. Should be called after
757 Create().
758
759 This function can only be called from another thread context.
760 */
761 wxThreadError Run();
762
763 /**
764 Sets the thread concurrency level for this process.
765
766 This is, roughly, the number of threads that the system tries to schedule
767 to run in parallel.
768 The value of 0 for @a level may be used to set the default one.
769
770 @return @true on success or @false otherwise (for example, if this function is
771 not implemented for this platform -- currently everything except Solaris).
772 */
773 static bool SetConcurrency(size_t level);
774
775 /**
776 Sets the priority of the thread, between 0 and 100.
777 It can only be set after calling Create() but before calling Run().
778
779 The following priorities are defined:
780 - @b WXTHREAD_MIN_PRIORITY: 0
781 - @b WXTHREAD_DEFAULT_PRIORITY: 50
782 - @b WXTHREAD_MAX_PRIORITY: 100
783 */
784 void SetPriority(int priority);
785
786 /**
787 Pauses the thread execution for the given amount of time.
788
789 This is the same as wxMilliSleep().
790 */
791 static void Sleep(unsigned long milliseconds);
792
793 /**
794 This function should be called periodically by the thread to ensure that
795 calls to Pause() and Delete() will work.
796
797 If it returns @true, the thread should exit as soon as possible.
798 Notice that under some platforms (POSIX), implementation of Pause() also
799 relies on this function being called, so not calling it would prevent
800 both stopping and suspending thread from working.
801 */
802 virtual bool TestDestroy();
803
804 /**
805 Return the thread object for the calling thread.
806
807 @NULL is returned if the calling thread is the main (GUI) thread, but
808 IsMain() should be used to test whether the thread is really the main one
809 because @NULL may also be returned for the thread not created with wxThread
810 class. Generally speaking, the return value for such a thread is undefined.
811 */
812 static wxThread* This();
813
814 /**
815 Waits for a joinable thread to terminate and returns the value the thread
816 returned from Entry() or @c (ExitCode)-1 on error. Notice that, unlike
817 Delete() doesn't cancel the thread in any way so the caller waits for as
818 long as it takes to the thread to exit.
819
820 You can only Wait() for joinable (not detached) threads.
821 This function can only be called from another thread context.
822
823 See @ref thread_deletion for a broader explanation of this routine.
824 */
825 ExitCode Wait() const;
826
827 /**
828 Give the rest of the thread time slice to the system allowing the other
829 threads to run.
830
831 Note that using this function is @b strongly discouraged, since in
832 many cases it indicates a design weakness of your threading model
833 (as does using Sleep() functions).
834
835 Threads should use the CPU in an efficient manner, i.e. they should
836 do their current work efficiently, then as soon as the work is done block
837 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
838 get signalled e.g. by other threads or a user device once further thread
839 work is available.
840 Using Yield() or Sleep() indicates polling-type behaviour, since we're
841 fuzzily giving up our timeslice and wait until sometime later we'll get
842 reactivated, at which time we realize that there isn't really much to do
843 and Yield() again...
844
845 The most critical characteristic of Yield() is that it's operating system
846 specific: there may be scheduler changes which cause your thread to not
847 wake up relatively soon again, but instead many seconds later,
848 causing huge performance issues for your application.
849
850 <strong>
851 With a well-behaving, CPU-efficient thread the operating system is likely
852 to properly care for its reactivation the moment it needs it, whereas with
853 non-deterministic, Yield-using threads all bets are off and the system
854 scheduler is free to penalize drastically</strong>, and this effect gets worse
855 with increasing system load due to less free CPU resources available.
856 You may refer to various Linux kernel @c sched_yield discussions for more
857 information.
858
859 See also Sleep().
860 */
861 static void Yield();
862
863 protected:
864
865 /**
866 This is the entry point of the thread.
867
868 This function is pure virtual and must be implemented by any derived class.
869 The thread execution will start here.
870
871 The returned value is the thread exit code which is only useful for
872 joinable threads and is the value returned by Wait().
873 This function is called by wxWidgets itself and should never be called
874 directly.
875 */
876 virtual ExitCode Entry();
877
878 /**
879 This is a protected function of the wxThread class and thus can only be called
880 from a derived class. It also can only be called in the context of this
881 thread, i.e. a thread can only exit from itself, not from another thread.
882
883 This function will terminate the OS thread (i.e. stop the associated path of
884 execution) and also delete the associated C++ object for detached threads.
885 OnExit() will be called just before exiting.
886 */
887 void Exit(ExitCode exitcode = 0);
888 };
889
890
891 /** See wxSemaphore. */
892 enum wxSemaError
893 {
894 wxSEMA_NO_ERROR = 0,
895 wxSEMA_INVALID, //!< semaphore hasn't been initialized successfully
896 wxSEMA_BUSY, //!< returned by TryWait() if Wait() would block
897 wxSEMA_TIMEOUT, //!< returned by WaitTimeout()
898 wxSEMA_OVERFLOW, //!< Post() would increase counter past the max
899 wxSEMA_MISC_ERROR
900 };
901
902 /**
903 @class wxSemaphore
904
905 wxSemaphore is a counter limiting the number of threads concurrently accessing
906 a shared resource. This counter is always between 0 and the maximum value
907 specified during the semaphore creation. When the counter is strictly greater
908 than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
909 counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
910 block and only return when the semaphore counter becomes strictly positive
911 again as the result of calling wxSemaphore::Post which increments the counter.
912
913 In general, semaphores are useful to restrict access to a shared resource
914 which can only be accessed by some fixed number of clients at the same time.
915 For example, when modeling a hotel reservation system a semaphore with the counter
916 equal to the total number of available rooms could be created. Each time a room
917 is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
918 and each time a room is freed it should be released by calling wxSemaphore::Post.
919
920 @library{wxbase}
921 @category{threading}
922 */
923 class wxSemaphore
924 {
925 public:
926 /**
927 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
928 there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
929 mutex (but unlike a mutex it can be released by a thread different from the one
930 which acquired it).
931
932 @a initialcount is the initial value of the semaphore which must be between
933 0 and @a maxcount (if it is not set to 0).
934 */
935 wxSemaphore(int initialcount = 0, int maxcount = 0);
936
937 /**
938 Destructor is not virtual, don't use this class polymorphically.
939 */
940 ~wxSemaphore();
941
942 /**
943 Increments the semaphore count and signals one of the waiting
944 threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
945 would increase the counter past the maximum.
946
947 @return One of:
948 - wxSEMA_NO_ERROR: There was no error.
949 - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
950 - wxSEMA_OVERFLOW: Post() would increase counter past the max.
951 - wxSEMA_MISC_ERROR: Miscellaneous error.
952 */
953 wxSemaError Post();
954
955 /**
956 Same as Wait(), but returns immediately.
957
958 @return One of:
959 - wxSEMA_NO_ERROR: There was no error.
960 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
961 - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
962 - wxSEMA_MISC_ERROR: Miscellaneous error.
963 */
964 wxSemaError TryWait();
965
966 /**
967 Wait indefinitely until the semaphore count becomes strictly positive
968 and then decrement it and return.
969
970 @return One of:
971 - wxSEMA_NO_ERROR: There was no error.
972 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
973 - wxSEMA_MISC_ERROR: Miscellaneous error.
974 */
975 wxSemaError Wait();
976
977 /**
978 Same as Wait(), but with a timeout limit.
979
980 @return One of:
981 - wxSEMA_NO_ERROR: There was no error.
982 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
983 - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
984 - wxSEMA_MISC_ERROR: Miscellaneous error.
985 */
986 wxSemaError WaitTimeout(unsigned longtimeout_millis);
987 };
988
989
990
991 /**
992 @class wxMutexLocker
993
994 This is a small helper class to be used with wxMutex objects.
995
996 A wxMutexLocker acquires a mutex lock in the constructor and releases
997 (or unlocks) the mutex in the destructor making it much more difficult to
998 forget to release a mutex (which, in general, will promptly lead to serious
999 problems). See wxMutex for an example of wxMutexLocker usage.
1000
1001 @library{wxbase}
1002 @category{threading}
1003
1004 @see wxMutex, wxCriticalSectionLocker
1005 */
1006 class wxMutexLocker
1007 {
1008 public:
1009 /**
1010 Constructs a wxMutexLocker object associated with mutex and locks it.
1011 Call IsOk() to check if the mutex was successfully locked.
1012 */
1013 wxMutexLocker(wxMutex& mutex);
1014
1015 /**
1016 Destructor releases the mutex if it was successfully acquired in the ctor.
1017 */
1018 ~wxMutexLocker();
1019
1020 /**
1021 Returns @true if mutex was acquired in the constructor, @false otherwise.
1022 */
1023 bool IsOk() const;
1024 };
1025
1026
1027 /**
1028 The possible wxMutex kinds.
1029 */
1030 enum wxMutexType
1031 {
1032 /** Normal non-recursive mutex: try to always use this one. */
1033 wxMUTEX_DEFAULT,
1034
1035 /** Recursive mutex: don't use these ones with wxCondition. */
1036 wxMUTEX_RECURSIVE
1037 };
1038
1039
1040 /**
1041 The possible wxMutex errors.
1042 */
1043 enum wxMutexError
1044 {
1045 /** The operation completed successfully. */
1046 wxMUTEX_NO_ERROR = 0,
1047
1048 /** The mutex hasn't been initialized. */
1049 wxMUTEX_INVALID,
1050
1051 /** The mutex is already locked by the calling thread. */
1052 wxMUTEX_DEAD_LOCK,
1053
1054 /** The mutex is already locked by another thread. */
1055 wxMUTEX_BUSY,
1056
1057 /** An attempt to unlock a mutex which is not locked. */
1058 wxMUTEX_UNLOCKED,
1059
1060 /** wxMutex::LockTimeout() has timed out. */
1061 wxMUTEX_TIMEOUT,
1062
1063 /** Any other error */
1064 wxMUTEX_MISC_ERROR
1065 };
1066
1067
1068 /**
1069 @class wxMutex
1070
1071 A mutex object is a synchronization object whose state is set to signaled when
1072 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
1073 from its usefulness in coordinating mutually-exclusive access to a shared
1074 resource as only one thread at a time can own a mutex object.
1075
1076 Mutexes may be recursive in the sense that a thread can lock a mutex which it
1077 had already locked before (instead of dead locking the entire process in this
1078 situation by starting to wait on a mutex which will never be released while the
1079 thread is waiting) but using them is not recommended under Unix and they are
1080 @b not recursive by default. The reason for this is that recursive
1081 mutexes are not supported by all Unix flavours and, worse, they cannot be used
1082 with wxCondition.
1083
1084 For example, when several threads use the data stored in the linked list,
1085 modifications to the list should only be allowed to one thread at a time
1086 because during a new node addition the list integrity is temporarily broken
1087 (this is also called @e program invariant).
1088
1089 @code
1090 // this variable has an "s_" prefix because it is static: seeing an "s_" in
1091 // a multithreaded program is in general a good sign that you should use a
1092 // mutex (or a critical section)
1093 static wxMutex *s_mutexProtectingTheGlobalData;
1094
1095 // we store some numbers in this global array which is presumably used by
1096 // several threads simultaneously
1097 wxArrayInt s_data;
1098
1099 void MyThread::AddNewNode(int num)
1100 {
1101 // ensure that no other thread accesses the list
1102 s_mutexProtectingTheGlobalList->Lock();
1103
1104 s_data.Add(num);
1105
1106 s_mutexProtectingTheGlobalList->Unlock();
1107 }
1108
1109 // return true if the given number is greater than all array elements
1110 bool MyThread::IsGreater(int num)
1111 {
1112 // before using the list we must acquire the mutex
1113 wxMutexLocker lock(s_mutexProtectingTheGlobalData);
1114
1115 size_t count = s_data.Count();
1116 for ( size_t n = 0; n < count; n++ )
1117 {
1118 if ( s_data[n] > num )
1119 return false;
1120 }
1121
1122 return true;
1123 }
1124 @endcode
1125
1126 Notice how wxMutexLocker was used in the second function to ensure that the
1127 mutex is unlocked in any case: whether the function returns true or false
1128 (because the destructor of the local object lock is always called). Using
1129 this class instead of directly using wxMutex is, in general safer and is
1130 even more so if your program uses C++ exceptions.
1131
1132 @library{wxbase}
1133 @category{threading}
1134
1135 @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
1136 */
1137 class wxMutex
1138 {
1139 public:
1140 /**
1141 Default constructor.
1142 */
1143 wxMutex(wxMutexType type = wxMUTEX_DEFAULT);
1144
1145 /**
1146 Destroys the wxMutex object.
1147 */
1148 ~wxMutex();
1149
1150 /**
1151 Locks the mutex object.
1152 This is equivalent to LockTimeout() with infinite timeout.
1153
1154 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
1155 */
1156 wxMutexError Lock();
1157
1158 /**
1159 Try to lock the mutex object during the specified time interval.
1160
1161 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
1162 */
1163 wxMutexError LockTimeout(unsigned long msec);
1164
1165 /**
1166 Tries to lock the mutex object. If it can't, returns immediately with an error.
1167
1168 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
1169 */
1170 wxMutexError TryLock();
1171
1172 /**
1173 Unlocks the mutex object.
1174
1175 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
1176 */
1177 wxMutexError Unlock();
1178 };
1179
1180
1181
1182 // ============================================================================
1183 // Global functions/macros
1184 // ============================================================================
1185
1186 /** @ingroup group_funcmacro_thread */
1187 //@{
1188
1189 /**
1190 This macro declares a (static) critical section object named @a cs if
1191 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1192
1193 @header{wx/thread.h}
1194 */
1195 #define wxCRIT_SECT_DECLARE(cs)
1196
1197 /**
1198 This macro declares a critical section object named @a cs if
1199 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
1200 the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
1201 declare a class or struct member which explains its name.
1202
1203 @header{wx/thread.h}
1204 */
1205 #define wxCRIT_SECT_DECLARE_MEMBER(cs)
1206
1207 /**
1208 This macro creates a wxCriticalSectionLocker named @a name and associated
1209 with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
1210 if it is 0.
1211
1212 @header{wx/thread.h}
1213 */
1214 #define wxCRIT_SECT_LOCKER(name, cs)
1215
1216 /**
1217 This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
1218 creates a static critical section object and also the lock object
1219 associated with it. Because of this, it can be only used inside a function,
1220 not at global scope. For example:
1221
1222 @code
1223 int IncCount()
1224 {
1225 static int s_counter = 0;
1226
1227 wxCRITICAL_SECTION(counter);
1228
1229 return ++s_counter;
1230 }
1231 @endcode
1232
1233 Note that this example assumes that the function is called the first time
1234 from the main thread so that the critical section object is initialized
1235 correctly by the time other threads start calling it, if this is not the
1236 case this approach can @b not be used and the critical section must be made
1237 a global instead.
1238
1239 @header{wx/thread.h}
1240 */
1241 #define wxCRITICAL_SECTION(name)
1242
1243 /**
1244 This macro is equivalent to
1245 @ref wxCriticalSection::Leave "critical_section.Leave()" if
1246 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1247
1248 @header{wx/thread.h}
1249 */
1250 #define wxLEAVE_CRIT_SECT(critical_section)
1251
1252 /**
1253 This macro is equivalent to
1254 @ref wxCriticalSection::Enter "critical_section.Enter()" if
1255 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1256
1257 @header{wx/thread.h}
1258 */
1259 #define wxENTER_CRIT_SECT(critical_section)
1260
1261 /**
1262 Returns @true if this thread is the main one. Always returns @true if
1263 @c wxUSE_THREADS is 0.
1264
1265 @header{wx/thread.h}
1266 */
1267 bool wxIsMainThread();
1268
1269 /**
1270 This function must be called when any thread other than the main GUI thread
1271 wants to get access to the GUI library. This function will block the
1272 execution of the calling thread until the main thread (or any other thread
1273 holding the main GUI lock) leaves the GUI library and no other thread will
1274 enter the GUI library until the calling thread calls wxMutexGuiLeave().
1275
1276 Typically, these functions are used like this:
1277
1278 @code
1279 void MyThread::Foo(void)
1280 {
1281 // before doing any GUI calls we must ensure that
1282 // this thread is the only one doing it!
1283
1284 wxMutexGuiEnter();
1285
1286 // Call GUI here:
1287 my_window-DrawSomething();
1288
1289 wxMutexGuiLeave();
1290 }
1291 @endcode
1292
1293 This function is only defined on platforms which support preemptive
1294 threads.
1295
1296 @note Under GTK, no creation of top-level windows is allowed in any thread
1297 but the main one.
1298
1299 @header{wx/thread.h}
1300 */
1301 void wxMutexGuiEnter();
1302
1303 /**
1304 This function is only defined on platforms which support preemptive
1305 threads.
1306
1307 @see wxMutexGuiEnter()
1308
1309 @header{wx/thread.h}
1310 */
1311 void wxMutexGuiLeave();
1312
1313 //@}
1314