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