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