]> git.saurik.com Git - wxWidgets.git/blame - interface/wx/thread.h
Move POSIX implementation of wxThread::Create() to wxThreadInternal.
[wxWidgets.git] / interface / wx / thread.h
CommitLineData
23324ae1
FM
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.h
78e87bf7 3// Purpose: interface of all thread-related wxWidgets classes
23324ae1
FM
4// Author: wxWidgets team
5// RCS-ID: $Id$
526954c5 6// Licence: wxWindows licence
23324ae1
FM
7/////////////////////////////////////////////////////////////////////////////
8
78e87bf7
FM
9
10/** See wxCondition. */
11enum wxCondError
12{
13 wxCOND_NO_ERROR = 0,
14 wxCOND_INVALID,
15 wxCOND_TIMEOUT, //!< WaitTimeout() has timed out
16 wxCOND_MISC_ERROR
17};
18
19
23324ae1
FM
20/**
21 @class wxCondition
7c913512 22
78e87bf7
FM
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.
7c913512 26
23324ae1
FM
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
7c913512 30 perfect because in this particular case it would be much better to just
78e87bf7
FM
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.
7c913512 102
23324ae1 103 @library{wxbase}
27608f11 104 @category{threading}
7c913512 105
e54c96f1 106 @see wxThread, wxMutex
23324ae1 107*/
7c913512 108class wxCondition
23324ae1
FM
109{
110public:
111 /**
78e87bf7
FM
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.
23324ae1
FM
115 */
116 wxCondition(wxMutex& mutex);
117
118 /**
78e87bf7
FM
119 Destroys the wxCondition object.
120
121 The destructor is not virtual so this class should not be used polymorphically.
23324ae1
FM
122 */
123 ~wxCondition();
124
125 /**
78e87bf7
FM
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.
3c4f71cc 130
4cc4bfaf 131 @see Signal()
23324ae1 132 */
7323ff1a 133 wxCondError Broadcast();
23324ae1
FM
134
135 /**
7c913512 136 Returns @true if the object had been initialized successfully, @false
23324ae1
FM
137 if an error occurred.
138 */
328f5751 139 bool IsOk() const;
23324ae1
FM
140
141 /**
78e87bf7
FM
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
23324ae1
FM
149 Note that this method may be called whether the mutex associated with this
150 condition is locked or not.
3c4f71cc 151
4cc4bfaf 152 @see Broadcast()
23324ae1 153 */
50ec54b6 154 wxCondError Signal();
23324ae1
FM
155
156 /**
157 Waits until the condition is signalled.
78e87bf7 158
23324ae1 159 This method atomically releases the lock on the mutex associated with this
78e87bf7
FM
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.
3c4f71cc 170
4cc4bfaf 171 @see WaitTimeout()
23324ae1
FM
172 */
173 wxCondError Wait();
174
175 /**
176 Waits until the condition is signalled or the timeout has elapsed.
78e87bf7
FM
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.
3c4f71cc 180
7c913512 181 @param milliseconds
4cc4bfaf 182 Timeout in milliseconds
78e87bf7
FM
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.
23324ae1
FM
187 */
188 wxCondError WaitTimeout(unsigned long milliseconds);
189};
190
e54c96f1 191
23324ae1
FM
192/**
193 @class wxCriticalSectionLocker
7c913512 194
78e87bf7
FM
195 This is a small helper class to be used with wxCriticalSection objects.
196
197 A wxCriticalSectionLocker enters the critical section in the constructor and
198 leaves it in the destructor making it much more difficult to forget to leave
199 a critical section (which, in general, will lead to serious and difficult
200 to debug problems).
7c913512 201
23324ae1 202 Example of using it:
7c913512 203
23324ae1
FM
204 @code
205 void Set Foo()
206 {
207 // gs_critSect is some (global) critical section guarding access to the
208 // object "foo"
209 wxCriticalSectionLocker locker(gs_critSect);
7c913512 210
23324ae1
FM
211 if ( ... )
212 {
213 // do something
214 ...
7c913512 215
23324ae1
FM
216 return;
217 }
7c913512 218
23324ae1
FM
219 // do something else
220 ...
7c913512 221
23324ae1
FM
222 return;
223 }
224 @endcode
7c913512 225
23324ae1
FM
226 Without wxCriticalSectionLocker, you would need to remember to manually leave
227 the critical section before each @c return.
7c913512 228
23324ae1 229 @library{wxbase}
27608f11 230 @category{threading}
7c913512 231
e54c96f1 232 @see wxCriticalSection, wxMutexLocker
23324ae1 233*/
7c913512 234class wxCriticalSectionLocker
23324ae1
FM
235{
236public:
237 /**
238 Constructs a wxCriticalSectionLocker object associated with given
4cc4bfaf 239 @a criticalsection and enters it.
23324ae1
FM
240 */
241 wxCriticalSectionLocker(wxCriticalSection& criticalsection);
242
243 /**
244 Destructor leaves the critical section.
245 */
246 ~wxCriticalSectionLocker();
247};
248
249
e54c96f1 250
23324ae1
FM
251/**
252 @class wxThreadHelper
7c913512 253
23324ae1 254 The wxThreadHelper class is a mix-in class that manages a single background
5cba3a25
FM
255 thread, either detached or joinable (see wxThread for the differences).
256 By deriving from wxThreadHelper, a class can implement the thread
78e87bf7
FM
257 code in its own wxThreadHelper::Entry() method and easily share data and
258 synchronization objects between the main thread and the worker thread.
259
260 Doing this prevents the awkward passing of pointers that is needed when the
261 original object in the main thread needs to synchronize with its worker thread
262 in its own wxThread derived object.
263
264 For example, wxFrame may need to make some calculations in a background thread
265 and then display the results of those calculations in the main window.
266
267 Ordinarily, a wxThread derived object would be created with the calculation
268 code implemented in wxThread::Entry. To access the inputs to the calculation,
5cba3a25 269 the frame object would often need to pass a pointer to itself to the thread object.
78e87bf7 270 Similarly, the frame object would hold a pointer to the thread object.
5cba3a25 271
78e87bf7
FM
272 Shared data and synchronization objects could be stored in either object
273 though the object without the data would have to access the data through
274 a pointer.
5cba3a25 275 However with wxThreadHelper the frame object and the thread object are
78e87bf7 276 treated as the same object. Shared data and synchronization variables are
23324ae1
FM
277 stored in the single object, eliminating a layer of indirection and the
278 associated pointers.
7c913512 279
5cba3a25
FM
280 Example:
281 @code
3a567740 282 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent);
848f8788 283
5cba3a25
FM
284 class MyFrame : public wxFrame, public wxThreadHelper
285 {
286 public:
848f8788 287 MyFrame(...) { ... }
5cba3a25
FM
288 ~MyFrame()
289 {
848f8788
FM
290 // it's better to do any thread cleanup in the OnClose()
291 // event handler, rather than in the destructor.
292 // This is because the event loop for a top-level window is not
293 // active anymore when its destructor is called and if the thread
294 // sends events when ending, they won't be processed unless
295 // you ended the thread from OnClose.
296 // See @ref overview_windowdeletion for more info.
5cba3a25
FM
297 }
298
299 ...
300 void DoStartALongTask();
3a567740 301 void OnThreadUpdate(wxThreadEvent& evt);
848f8788 302 void OnClose(wxCloseEvent& evt);
5cba3a25 303 ...
848f8788
FM
304
305 protected:
306 virtual wxThread::ExitCode Entry();
307
308 // the output data of the Entry() routine:
309 char m_data[1024];
310 wxCriticalSection m_dataCS; // protects field above
311
a0e9a5df 312 wxDECLARE_EVENT_TABLE();
848f8788
FM
313 };
314
3a567740 315 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent)
a0e9a5df 316 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
848f8788
FM
317 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_UPDATE, MyFrame::OnThreadUpdate)
318 EVT_CLOSE(MyFrame::OnClose)
a0e9a5df 319 wxEND_EVENT_TABLE()
5cba3a25
FM
320
321 void MyFrame::DoStartALongTask()
322 {
323 // we want to start a long task, but we don't want our GUI to block
324 // while it's executed, so we use a thread to do it.
848f8788 325 if (CreateThread(wxTHREAD_JOINABLE) != wxTHREAD_NO_ERROR)
5cba3a25
FM
326 {
327 wxLogError("Could not create the worker thread!");
328 return;
329 }
330
331 // go!
848f8788 332 if (GetThread()->Run() != wxTHREAD_NO_ERROR)
5cba3a25
FM
333 {
334 wxLogError("Could not run the worker thread!");
335 return;
336 }
337 }
848f8788
FM
338
339 wxThread::ExitCode MyFrame::Entry()
340 {
341 // IMPORTANT:
342 // this function gets executed in the secondary thread context!
343
344 int offset = 0;
345
346 // here we do our long task, periodically calling TestDestroy():
347 while (!GetThread()->TestDestroy())
348 {
349 // since this Entry() is implemented in MyFrame context we don't
350 // need any pointer to access the m_data, m_processedData, m_dataCS
351 // variables... very nice!
352
353 // this is an example of the generic structure of a download thread:
354 char buffer[1024];
355 download_chunk(buffer, 1024); // this takes time...
356
357 {
57ab6f23 358 // ensure no one reads m_data while we write it
848f8788
FM
359 wxCriticalSectionLocker lock(m_dataCS);
360 memcpy(m_data+offset, buffer, 1024);
361 offset += 1024;
362 }
363
364
365 // VERY IMPORTANT: do not call any GUI function inside this
366 // function; rather use wxQueueEvent():
3a567740 367 wxQueueEvent(this, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
848f8788
FM
368 // we used pointer 'this' assuming it's safe; see OnClose()
369 }
370
371 // TestDestroy() returned true (which means the main thread asked us
372 // to terminate as soon as possible) or we ended the long task...
373 return (wxThread::ExitCode)0;
374 }
375
376 void MyFrame::OnClose(wxCloseEvent&)
377 {
378 // important: before terminating, we _must_ wait for our joinable
379 // thread to end, if it's running; in fact it uses variables of this
380 // instance and posts events to *this event handler
381
382 if (GetThread() && // DoStartALongTask() may have not been called
383 GetThread()->IsRunning())
384 GetThread()->Wait();
385
386 Destroy();
387 }
388
3a567740 389 void MyFrame::OnThreadUpdate(wxThreadEvent& evt)
848f8788
FM
390 {
391 // ...do something... e.g. m_pGauge->Pulse();
392
393 // read some parts of m_data just for fun:
394 wxCriticalSectionLocker lock(m_dataCS);
395 wxPrintf("%c", m_data[100]);
396 }
5cba3a25
FM
397 @endcode
398
23324ae1 399 @library{wxbase}
27608f11 400 @category{threading}
7c913512 401
3a567740 402 @see wxThread, wxThreadEvent
23324ae1 403*/
7c913512 404class wxThreadHelper
23324ae1
FM
405{
406public:
407 /**
5cba3a25
FM
408 This constructor simply initializes internal member variables and tells
409 wxThreadHelper which type the thread internally managed should be.
23324ae1 410 */
4ccf0566 411 wxThreadHelper(wxThreadKind kind = wxTHREAD_JOINABLE);
23324ae1
FM
412
413 /**
5cba3a25
FM
414 The destructor frees the resources associated with the thread, forcing
415 it to terminate (it uses wxThread::Kill function).
416
417 Because of the wxThread::Kill unsafety, you should always wait
418 (with wxThread::Wait) for joinable threads to end or call wxThread::Delete
419 on detached threads, instead of relying on this destructor for stopping
420 the thread.
23324ae1 421 */
adaaa686 422 virtual ~wxThreadHelper();
23324ae1 423
23324ae1 424 /**
78e87bf7
FM
425 This is the entry point of the thread.
426
427 This function is pure virtual and must be implemented by any derived class.
428 The thread execution will start here.
429
848f8788
FM
430 You'll typically want your Entry() to look like:
431 @code
432 wxThread::ExitCode Entry()
433 {
434 while (!GetThread()->TestDestroy())
435 {
436 // ... do some work ...
437
438 if (IsWorkCompleted)
439 break;
440
441 if (HappenedStoppingError)
442 return (wxThread::ExitCode)1; // failure
443 }
444
445 return (wxThread::ExitCode)0; // success
446 }
447 @endcode
448
23324ae1 449 The returned value is the thread exit code which is only useful for
78e87bf7
FM
450 joinable threads and is the value returned by @c "GetThread()->Wait()".
451
23324ae1
FM
452 This function is called by wxWidgets itself and should never be called
453 directly.
454 */
5267aefd 455 virtual ExitCode Entry() = 0;
23324ae1 456
df191bfe
VZ
457 /**
458 Callback called by Delete() before actually deleting the thread.
459
460 This function can be overridden by the derived class to perform some
461 specific task when the thread is gracefully destroyed. Notice that it
462 will be executed in the context of the thread that called Delete() and
463 <b>not</b> in this thread's context.
464
465 TestDestroy() will be true for the thread before OnDelete() gets
466 executed.
467
468 @since 2.9.2
469
470 @see OnKill()
471 */
472 virtual void OnDelete();
473
474 /**
475 Callback called by Kill() before actually killing the thread.
476
477 This function can be overridden by the derived class to perform some
478 specific task when the thread is terminated. Notice that it will be
479 executed in the context of the thread that called Kill() and <b>not</b>
480 in this thread's context.
481
482 @since 2.9.2
483
484 @see OnDelete()
485 */
486 virtual void OnKill();
487
9eab0f6c
FM
488 /**
489 @deprecated
490 Use CreateThread() instead.
491 */
492 wxThreadError Create(unsigned int stackSize = 0);
493
551266a9 494 /**
848f8788 495 Creates a new thread of the given @a kind.
551266a9
FM
496
497 The thread object is created in the suspended state, and you
5cba3a25 498 should call @ref wxThread::Run "GetThread()->Run()" to start running it.
551266a9
FM
499
500 You may optionally specify the stack size to be allocated to it (ignored
848f8788 501 on platforms that don't support setting it explicitly, e.g. Unix).
5cba3a25 502
551266a9
FM
503 @return One of the ::wxThreadError enum values.
504 */
848f8788
FM
505 wxThreadError CreateThread(wxThreadKind kind = wxTHREAD_JOINABLE,
506 unsigned int stackSize = 0);
551266a9 507
23324ae1 508 /**
5cba3a25
FM
509 This is a public function that returns the wxThread object associated with
510 the thread.
23324ae1 511 */
adaaa686 512 wxThread* GetThread() const;
848f8788
FM
513
514 /**
515 Returns the last type of thread given to the CreateThread() function
516 or to the constructor.
517 */
518 wxThreadKind GetThreadKind() const;
23324ae1
FM
519};
520
3ad41c28
RR
521/**
522 Possible critical section types
523*/
23324ae1 524
3ad41c28
RR
525enum wxCriticalSectionType
526{
527 wxCRITSEC_DEFAULT,
528 /** Recursive critical section under both Windows and Unix */
529
78e87bf7 530 wxCRITSEC_NON_RECURSIVE
3ad41c28
RR
531 /** Non-recursive critical section under Unix, recursive under Windows */
532};
e54c96f1 533
23324ae1
FM
534/**
535 @class wxCriticalSection
7c913512 536
78e87bf7
FM
537 A critical section object is used for exactly the same purpose as a wxMutex.
538 The only difference is that under Windows platform critical sections are only
539 visible inside one process, while mutexes may be shared among processes,
540 so using critical sections is slightly more efficient.
541
542 The terminology is also slightly different: mutex may be locked (or acquired)
543 and unlocked (or released) while critical section is entered and left by the program.
7c913512 544
3ad41c28 545 Finally, you should try to use wxCriticalSectionLocker class whenever
7c913512 546 possible instead of directly using wxCriticalSection for the same reasons
57ab6f23 547 wxMutexLocker is preferable to wxMutex - please see wxMutex for an example.
7c913512 548
23324ae1 549 @library{wxbase}
27608f11 550 @category{threading}
7c913512 551
384a14ff
VS
552 @note Critical sections can be used before the wxWidgets library is fully
553 initialized. In particular, it's safe to create global
554 wxCriticalSection instances.
555
e54c96f1 556 @see wxThread, wxCondition, wxCriticalSectionLocker
23324ae1 557*/
7c913512 558class wxCriticalSection
23324ae1
FM
559{
560public:
561 /**
78e87bf7
FM
562 Default constructor initializes critical section object.
563 By default critical sections are recursive under Unix and Windows.
23324ae1 564 */
3ad41c28 565 wxCriticalSection( wxCriticalSectionType critSecType = wxCRITSEC_DEFAULT );
23324ae1
FM
566
567 /**
568 Destructor frees the resources.
569 */
570 ~wxCriticalSection();
571
572 /**
db034c52
FM
573 Enter the critical section (same as locking a mutex): if another thread
574 has already entered it, this call will block until the other thread
575 calls Leave().
78e87bf7 576 There is no error return for this function.
db034c52
FM
577
578 After entering the critical section protecting a data variable,
579 the thread running inside the critical section may safely use/modify it.
580
581 Note that entering the same critical section twice or more from the same
582 thread doesn't result in a deadlock; in this case in fact this function will
583 immediately return.
23324ae1
FM
584 */
585 void Enter();
586
b9697cb4
VZ
587 /**
588 Try to enter the critical section (same as trying to lock a mutex).
589 If it can't, immediately returns false.
590
591 @since 2.9.3
592 */
593 bool TryEnter();
594
23324ae1 595 /**
78e87bf7
FM
596 Leave the critical section allowing other threads use the global data
597 protected by it. There is no error return for this function.
23324ae1
FM
598 */
599 void Leave();
600};
601
b95a7c31
VZ
602/**
603 The possible thread wait types.
604
605 @since 2.9.2
606*/
607enum wxThreadWait
608{
609 /**
610 No events are processed while waiting.
611
612 This is the default under all platforms except for wxMSW.
613 */
614 wxTHREAD_WAIT_BLOCK,
615
616 /**
617 Yield for event dispatching while waiting.
618
619 This flag is dangerous as it exposes the program using it to unexpected
620 reentrancies in the same way as calling wxYield() function does so you
621 are strongly advised to avoid its use and not wait for the thread
622 termination from the main (GUI) thread at all to avoid making your
623 application unresponsive.
624
625 Also notice that this flag is not portable as it is only implemented in
626 wxMSW and simply ignored under the other platforms.
627 */
628 wxTHREAD_WAIT_YIELD,
629
630 /**
631 Default wait mode for wxThread::Wait() and wxThread::Delete().
632
633 For compatibility reasons, the default wait mode is currently
634 wxTHREAD_WAIT_YIELD if WXWIN_COMPATIBILITY_2_8 is defined (and it is
635 by default). However, as mentioned above, you're strongly encouraged to
636 not use wxTHREAD_WAIT_YIELD and pass wxTHREAD_WAIT_BLOCK to wxThread
637 method explicitly.
638 */
639 wxTHREAD_WAIT_DEFAULT = wxTHREAD_WAIT_YIELD
640};
641
3ad41c28
RR
642/**
643 The possible thread kinds.
644*/
645enum wxThreadKind
646{
9c5313d1 647 /** Detached thread */
78e87bf7
FM
648 wxTHREAD_DETACHED,
649
9c5313d1 650 /** Joinable thread */
78e87bf7 651 wxTHREAD_JOINABLE
3ad41c28
RR
652};
653
654/**
655 The possible thread errors.
656*/
657enum wxThreadError
658{
9c5313d1 659 /** No error */
78e87bf7
FM
660 wxTHREAD_NO_ERROR = 0,
661
9c5313d1 662 /** No resource left to create a new thread. */
78e87bf7
FM
663 wxTHREAD_NO_RESOURCE,
664
9c5313d1 665 /** The thread is already running. */
78e87bf7
FM
666 wxTHREAD_RUNNING,
667
668 /** The thread isn't running. */
669 wxTHREAD_NOT_RUNNING,
670
9c5313d1 671 /** Thread we waited for had to be killed. */
78e87bf7
FM
672 wxTHREAD_KILLED,
673
9c5313d1 674 /** Some other error */
78e87bf7 675 wxTHREAD_MISC_ERROR
3ad41c28
RR
676};
677
23324ae1
FM
678/**
679 @class wxThread
7c913512 680
78e87bf7
FM
681 A thread is basically a path of execution through a program.
682 Threads are sometimes called @e light-weight processes, but the fundamental difference
23324ae1 683 between threads and processes is that memory spaces of different processes are
7c913512
FM
684 separated while all threads share the same address space.
685
23324ae1 686 While it makes it much easier to share common data between several threads, it
bb3e5526 687 also makes it much easier to shoot oneself in the foot, so careful use of
5cba3a25
FM
688 synchronization objects such as mutexes (see wxMutex) or critical sections
689 (see wxCriticalSection) is recommended.
690 In addition, don't create global thread objects because they allocate memory
691 in their constructor, which will cause problems for the memory checking system.
692
78e87bf7
FM
693
694 @section thread_types Types of wxThreads
695
696 There are two types of threads in wxWidgets: @e detached and @e joinable,
57ab6f23 697 modeled after the POSIX thread API. This is different from the Win32 API
78e87bf7
FM
698 where all threads are joinable.
699
4c51a665 700 By default wxThreads in wxWidgets use the @b detached behaviour.
5cba3a25
FM
701 Detached threads delete themselves once they have completed, either by themselves
702 when they complete processing or through a call to Delete(), and thus
703 @b must be created on the heap (through the new operator, for example).
704
705 Typically you'll want to store the instances of the detached wxThreads you
706 allocate, so that you can call functions on them.
707 Because of their nature however you'll need to always use a critical section
708 when accessing them:
709
710 @code
711 // declare a new type of event, to be used by our MyThread class:
3a567740
FM
712 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent);
713 wxDECLARE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent);
848f8788 714 class MyFrame;
5cba3a25
FM
715
716 class MyThread : public wxThread
717 {
718 public:
848f8788
FM
719 MyThread(MyFrame *handler)
720 : wxThread(wxTHREAD_DETACHED)
721 { m_pHandler = handler }
722 ~MyThread();
5cba3a25 723
848f8788
FM
724 protected:
725 virtual ExitCode Entry();
726 MyFrame *m_pHandler;
5cba3a25
FM
727 };
728
729 class MyFrame : public wxFrame
730 {
731 public:
732 ...
848f8788
FM
733 ~MyFrame()
734 {
735 // it's better to do any thread cleanup in the OnClose()
736 // event handler, rather than in the destructor.
737 // This is because the event loop for a top-level window is not
738 // active anymore when its destructor is called and if the thread
739 // sends events when ending, they won't be processed unless
740 // you ended the thread from OnClose.
741 // See @ref overview_windowdeletion for more info.
742 }
5cba3a25
FM
743 ...
744 void DoStartThread();
745 void DoPauseThread();
746
848f8788 747 // a resume routine would be nearly identic to DoPauseThread()
5cba3a25
FM
748 void DoResumeThread() { ... }
749
3a567740
FM
750 void OnThreadUpdate(wxThreadEvent&);
751 void OnThreadCompletion(wxThreadEvent&);
848f8788 752 void OnClose(wxCloseEvent&);
5cba3a25
FM
753
754 protected:
755 MyThread *m_pThread;
848f8788 756 wxCriticalSection m_pThreadCS; // protects the m_pThread pointer
5cba3a25 757
a0e9a5df 758 wxDECLARE_EVENT_TABLE();
5cba3a25
FM
759 };
760
a0e9a5df 761 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
848f8788
FM
762 EVT_CLOSE(MyFrame::OnClose)
763 EVT_MENU(Minimal_Start, MyFrame::DoStartThread)
764 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_UPDATE, MyFrame::OnThreadUpdate)
765 EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_MYTHREAD_COMPLETED, MyFrame::OnThreadCompletion)
a0e9a5df 766 wxEND_EVENT_TABLE()
848f8788 767
3a567740
FM
768 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_COMPLETED, wxThreadEvent)
769 wxDEFINE_EVENT(wxEVT_COMMAND_MYTHREAD_UPDATE, wxThreadEvent)
848f8788 770
5cba3a25
FM
771 void MyFrame::DoStartThread()
772 {
848f8788 773 m_pThread = new MyThread(this);
5cba3a25
FM
774
775 if ( m_pThread->Create() != wxTHREAD_NO_ERROR )
776 {
777 wxLogError("Can't create the thread!");
778 delete m_pThread;
779 m_pThread = NULL;
780 }
781 else
782 {
783 if (m_pThread->Run() != wxTHREAD_NO_ERROR )
784 {
785 wxLogError("Can't create the thread!");
786 delete m_pThread;
787 m_pThread = NULL;
788 }
789
790 // after the call to wxThread::Run(), the m_pThread pointer is "unsafe":
791 // at any moment the thread may cease to exist (because it completes its work).
792 // To avoid dangling pointers OnThreadExit() will set m_pThread
793 // to NULL when the thread dies.
794 }
795 }
796
848f8788
FM
797 wxThread::ExitCode MyThread::Entry()
798 {
799 while (!TestDestroy())
800 {
801 // ... do a bit of work...
802
3a567740 803 wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_UPDATE));
848f8788
FM
804 }
805
806 // signal the event handler that this thread is going to be destroyed
807 // NOTE: here we assume that using the m_pHandler pointer is safe,
808 // (in this case this is assured by the MyFrame destructor)
3a567740 809 wxQueueEvent(m_pHandler, new wxThreadEvent(wxEVT_COMMAND_MYTHREAD_COMPLETED));
848f8788
FM
810
811 return (wxThread::ExitCode)0; // success
812 }
813
814 MyThread::~MyThread()
815 {
816 wxCriticalSectionLocker enter(m_pHandler->m_pThreadCS);
817
818 // the thread is being destroyed; make sure not to leave dangling pointers around
819 m_pHandler->m_pThread = NULL;
820 }
821
3a567740 822 void MyFrame::OnThreadCompletion(wxThreadEvent&)
848f8788
FM
823 {
824 wxMessageOutputDebug().Printf("MYFRAME: MyThread exited!\n");
825 }
826
3a567740 827 void MyFrame::OnThreadUpdate(wxThreadEvent&)
5cba3a25 828 {
848f8788 829 wxMessageOutputDebug().Printf("MYFRAME: MyThread update...\n");
5cba3a25
FM
830 }
831
832 void MyFrame::DoPauseThread()
833 {
834 // anytime we access the m_pThread pointer we must ensure that it won't
848f8788
FM
835 // be modified in the meanwhile; since only a single thread may be
836 // inside a given critical section at a given time, the following code
837 // is safe:
838 wxCriticalSectionLocker enter(m_pThreadCS);
5cba3a25
FM
839
840 if (m_pThread) // does the thread still exist?
841 {
842 // without a critical section, once reached this point it may happen
843 // that the OS scheduler gives control to the MyThread::Entry() function,
844 // which in turn may return (because it completes its work) making
848f8788 845 // invalid the m_pThread pointer
5cba3a25
FM
846
847 if (m_pThread->Pause() != wxTHREAD_NO_ERROR )
848 wxLogError("Can't pause the thread!");
849 }
850 }
851
848f8788 852 void MyFrame::OnClose(wxCloseEvent&)
5cba3a25 853 {
848f8788
FM
854 {
855 wxCriticalSectionLocker enter(m_pThreadCS);
5cba3a25 856
848f8788
FM
857 if (m_pThread) // does the thread still exist?
858 {
89a76d5d 859 wxMessageOutputDebug().Printf("MYFRAME: deleting thread");
848f8788
FM
860
861 if (m_pThread->Delete() != wxTHREAD_NO_ERROR )
862 wxLogError("Can't delete the thread!");
863 }
864 } // exit from the critical section to give the thread
865 // the possibility to enter its destructor
866 // (which is guarded with m_pThreadCS critical section!)
867
868 while (1)
5cba3a25 869 {
848f8788
FM
870 { // was the ~MyThread() function executed?
871 wxCriticalSectionLocker enter(m_pThreadCS);
872 if (!m_pThread) break;
873 }
874
875 // wait for thread completion
876 wxThread::This()->Sleep(1);
5cba3a25 877 }
848f8788
FM
878
879 Destroy();
5cba3a25
FM
880 }
881 @endcode
882
848f8788
FM
883 For a more detailed and comprehensive example, see @sample{thread}.
884 For a simpler way to share data and synchronization objects between
885 the main and the secondary thread see wxThreadHelper.
886
5cba3a25 887 Conversely, @b joinable threads do not delete themselves when they are done
78e87bf7
FM
888 processing and as such are safe to create on the stack. Joinable threads
889 also provide the ability for one to get value it returned from Entry()
890 through Wait().
78e87bf7
FM
891 You shouldn't hurry to create all the threads joinable, however, because this
892 has a disadvantage as well: you @b must Wait() for a joinable thread or the
893 system resources used by it will never be freed, and you also must delete the
894 corresponding wxThread object yourself if you did not create it on the stack.
5cba3a25
FM
895 In contrast, detached threads are of the "fire-and-forget" kind: you only have
896 to start a detached thread and it will terminate and destroy itself.
78e87bf7
FM
897
898
899 @section thread_deletion wxThread Deletion
900
901 Regardless of whether it has terminated or not, you should call Wait() on a
5cba3a25 902 @b joinable thread to release its memory, as outlined in @ref thread_types.
78e87bf7
FM
903 If you created a joinable thread on the heap, remember to delete it manually
904 with the @c delete operator or similar means as only detached threads handle
905 this type of memory management.
906
5cba3a25 907 Since @b detached threads delete themselves when they are finished processing,
78e87bf7
FM
908 you should take care when calling a routine on one. If you are certain the
909 thread is still running and would like to end it, you may call Delete()
910 to gracefully end it (which implies that the thread will be deleted after
5cba3a25
FM
911 that call to Delete()). It should be implied that you should @b never attempt
912 to delete a detached thread with the @c delete operator or similar means.
913
914 As mentioned, Wait() or Delete() functions attempt to gracefully terminate a
915 joinable and a detached thread, respectively. They do this by waiting until
916 the thread in question calls TestDestroy() or ends processing (i.e. returns
78e87bf7
FM
917 from wxThread::Entry).
918
5cba3a25
FM
919 Obviously, if the thread does call TestDestroy() and does not end, the
920 thread which called Wait() or Delete() will come to halt.
921 This is why it's important to call TestDestroy() in the Entry() routine of
922 your threads as often as possible and immediately exit when it returns @true.
923
78e87bf7
FM
924 As a last resort you can end the thread immediately through Kill(). It is
925 strongly recommended that you do not do this, however, as it does not free
926 the resources associated with the object (although the wxThread object of
927 detached threads will still be deleted) and could leave the C runtime
928 library in an undefined state.
929
930
931 @section thread_secondary wxWidgets Calls in Secondary Threads
932
5cba3a25
FM
933 All threads other than the "main application thread" (the one running
934 wxApp::OnInit() or the one your main function runs in, for example) are
935 considered "secondary threads". These include all threads created by Create()
936 or the corresponding constructors.
78e87bf7
FM
937
938 GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe
939 at all in secondary threads and could end your application prematurely.
940 This is due to several reasons, including the underlying native API and
941 the fact that wxThread does not run a GUI event loop similar to other APIs
942 as MFC.
943
944 A workaround for some wxWidgets ports is calling wxMutexGUIEnter()
ae93dddf
FM
945 before any GUI calls and then calling wxMutexGUILeave() afterwords.
946 However, the recommended way is to simply process the GUI calls in the main
947 thread through an event that is posted by wxQueueEvent().
78e87bf7
FM
948 This does not imply that calls to these classes are thread-safe, however,
949 as most wxWidgets classes are not thread-safe, including wxString.
950
951
952 @section thread_poll Don't Poll a wxThread
953
954 A common problem users experience with wxThread is that in their main thread
955 they will check the thread every now and then to see if it has ended through
956 IsRunning(), only to find that their application has run into problems
4c51a665 957 because the thread is using the default behaviour (i.e. it's @b detached) and
5cba3a25
FM
958 has already deleted itself.
959 Naturally, they instead attempt to use joinable threads in place of the previous
4c51a665 960 behaviour. However, polling a wxThread for when it has ended is in general a
5cba3a25
FM
961 bad idea - in fact calling a routine on any running wxThread should be avoided
962 if possible. Instead, find a way to notify yourself when the thread has ended.
78e87bf7
FM
963
964 Usually you only need to notify the main thread, in which case you can
5cba3a25 965 post an event to it via wxQueueEvent().
78e87bf7
FM
966 In the case of secondary threads you can call a routine of another class
967 when the thread is about to complete processing and/or set the value of
968 a variable, possibly using mutexes (see wxMutex) and/or other synchronization
969 means if necessary.
bb3e5526 970
23324ae1 971 @library{wxbase}
27608f11 972 @category{threading}
78e87bf7 973
5cba3a25
FM
974 @see wxThreadHelper, wxMutex, wxCondition, wxCriticalSection,
975 @ref overview_thread
23324ae1 976*/
7c913512 977class wxThread
23324ae1
FM
978{
979public:
5cba3a25
FM
980 /**
981 The return type for the thread functions.
982 */
983 typedef void* ExitCode;
984
23324ae1 985 /**
8b9aed29 986 This constructor creates a new detached (default) or joinable C++
78e87bf7 987 thread object. It does not create or start execution of the real thread -
8b9aed29 988 for this you should use the Create() and Run() methods.
78e87bf7 989
4cc4bfaf 990 The possible values for @a kind parameters are:
8b9aed29
RR
991 - @b wxTHREAD_DETACHED - Creates a detached thread.
992 - @b wxTHREAD_JOINABLE - Creates a joinable thread.
23324ae1
FM
993 */
994 wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
995
996 /**
78e87bf7
FM
997 The destructor frees the resources associated with the thread.
998 Notice that you should never delete a detached thread -- you may only call
999 Delete() on it or wait until it terminates (and auto destructs) itself.
1000
1001 Because the detached threads delete themselves, they can only be allocated on the heap.
23324ae1 1002 Joinable threads should be deleted explicitly. The Delete() and Kill() functions
78e87bf7 1003 will not delete the C++ thread object. It is also safe to allocate them on stack.
23324ae1 1004 */
adaaa686 1005 virtual ~wxThread();
23324ae1
FM
1006
1007 /**
78e87bf7
FM
1008 Creates a new thread.
1009
1010 The thread object is created in the suspended state, and you should call Run()
1011 to start running it. You may optionally specify the stack size to be allocated
1012 to it (Ignored on platforms that don't support setting it explicitly,
1013 eg. Unix system without @c pthread_attr_setstacksize).
1014
1015 If you do not specify the stack size,the system's default value is used.
1016
1017 @warning
1018 It is a good idea to explicitly specify a value as systems'
1019 default values vary from just a couple of KB on some systems (BSD and
1020 OS/2 systems) to one or several MB (Windows, Solaris, Linux).
1021 So, if you have a thread that requires more than just a few KB of memory, you
1022 will have mysterious problems on some platforms but not on the common ones.
1023 On the other hand, just indicating a large stack size by default will give you
1024 performance issues on those systems with small default stack since those
1025 typically use fully committed memory for the stack.
1026 On the contrary, if you use a lot of threads (say several hundred),
57ab6f23 1027 virtual address space can get tight unless you explicitly specify a
78e87bf7 1028 smaller amount of thread stack space for each thread.
3c4f71cc 1029
d29a9a8a 1030 @return One of:
8b9aed29
RR
1031 - @b wxTHREAD_NO_ERROR - No error.
1032 - @b wxTHREAD_NO_RESOURCE - There were insufficient resources to create the thread.
1033 - @b wxTHREAD_NO_RUNNING - The thread is already running
23324ae1
FM
1034 */
1035 wxThreadError Create(unsigned int stackSize = 0);
1036
1037 /**
5cba3a25
FM
1038 Calling Delete() gracefully terminates a @b detached thread, either when
1039 the thread calls TestDestroy() or when it finishes processing.
78e87bf7 1040
b95a7c31
VZ
1041 @param rc
1042 The thread exit code, if rc is not NULL.
1043
1044 @param waitMode
1045 As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
1046 should be used as the wait mode even although currently
1047 wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
1048 new in wxWidgets 2.9.2.
1049
78e87bf7 1050 @note
848f8788
FM
1051 This function works on a joinable thread but in that case makes
1052 the TestDestroy() function of the thread return @true and then
1053 waits for its completion (i.e. it differs from Wait() because
1054 it asks the thread to terminate before waiting).
78e87bf7
FM
1055
1056 See @ref thread_deletion for a broader explanation of this routine.
23324ae1 1057 */
b95a7c31
VZ
1058 wxThreadError Delete(ExitCode *rc = NULL,
1059 wxThreadWait waitMode = wxTHREAD_WAIT_BLOCK);
23324ae1 1060
23324ae1
FM
1061 /**
1062 Returns the number of system CPUs or -1 if the value is unknown.
3c4f71cc 1063
c6427d4d
FM
1064 For multi-core systems the returned value is typically the total number
1065 of @e cores, since the OS usually abstract a single N-core CPU
1066 as N different cores.
1067
4cc4bfaf 1068 @see SetConcurrency()
23324ae1
FM
1069 */
1070 static int GetCPUCount();
1071
1072 /**
78e87bf7 1073 Returns the platform specific thread ID of the current thread as a long.
f9226383 1074
78e87bf7 1075 This can be used to uniquely identify threads, even if they are not wxThreads.
f9226383
VZ
1076
1077 @see GetMainId()
23324ae1 1078 */
382f12e4 1079 static wxThreadIdType GetCurrentId();
23324ae1
FM
1080
1081 /**
1082 Gets the thread identifier: this is a platform dependent number that uniquely
78e87bf7 1083 identifies the thread throughout the system during its existence
0824e369 1084 (i.e.\ the thread identifiers may be reused).
23324ae1 1085 */
5267aefd 1086 wxThreadIdType GetId() const;
23324ae1 1087
5159e014
FM
1088 /**
1089 Returns the thread kind as it was given in the ctor.
1090
1091 @since 2.9.0
1092 */
1093 wxThreadKind GetKind() const;
1094
f9226383
VZ
1095 /**
1096 Returns the thread ID of the main thread.
1097
1098 @see IsMain()
1099
1100 @since 2.9.1
1101 */
1102 static wxThreadIdType GetMainId();
1103
23324ae1 1104 /**
90e95e61 1105 Gets the priority of the thread, between 0 (lowest) and 100 (highest).
78e87bf7 1106
90e95e61 1107 @see SetPriority()
23324ae1 1108 */
5267aefd 1109 unsigned int GetPriority() const;
23324ae1
FM
1110
1111 /**
0824e369 1112 Returns @true if the thread is alive (i.e.\ started and not terminating).
78e87bf7 1113
23324ae1
FM
1114 Note that this function can only safely be used with joinable threads, not
1115 detached ones as the latter delete themselves and so when the real thread is
1116 no longer alive, it is not possible to call this function because
1117 the wxThread object no longer exists.
1118 */
328f5751 1119 bool IsAlive() const;
23324ae1
FM
1120
1121 /**
1122 Returns @true if the thread is of the detached kind, @false if it is a
78e87bf7 1123 joinable one.
23324ae1 1124 */
328f5751 1125 bool IsDetached() const;
23324ae1
FM
1126
1127 /**
1128 Returns @true if the calling thread is the main application thread.
f9226383
VZ
1129
1130 Main thread in the context of wxWidgets is the one which initialized
1131 the library.
1132
1133 @see GetMainId(), GetCurrentId()
23324ae1
FM
1134 */
1135 static bool IsMain();
1136
1137 /**
1138 Returns @true if the thread is paused.
1139 */
328f5751 1140 bool IsPaused() const;
23324ae1
FM
1141
1142 /**
1143 Returns @true if the thread is running.
78e87bf7 1144
7c913512 1145 This method may only be safely used for joinable threads, see the remark in
23324ae1
FM
1146 IsAlive().
1147 */
328f5751 1148 bool IsRunning() const;
23324ae1
FM
1149
1150 /**
78e87bf7
FM
1151 Immediately terminates the target thread.
1152
1153 @b "This function is dangerous and should be used with extreme care"
1154 (and not used at all whenever possible)! The resources allocated to the
1155 thread will not be freed and the state of the C runtime library may become
1156 inconsistent. Use Delete() for detached threads or Wait() for joinable
1157 threads instead.
1158
23324ae1
FM
1159 For detached threads Kill() will also delete the associated C++ object.
1160 However this will not happen for joinable threads and this means that you will
1161 still have to delete the wxThread object yourself to avoid memory leaks.
78e87bf7
FM
1162
1163 In neither case OnExit() of the dying thread will be called, so no
1164 thread-specific cleanup will be performed.
23324ae1
FM
1165 This function can only be called from another thread context, i.e. a thread
1166 cannot kill itself.
78e87bf7 1167
23324ae1
FM
1168 It is also an error to call this function for a thread which is not running or
1169 paused (in the latter case, the thread will be resumed first) -- if you do it,
8b9aed29 1170 a @b wxTHREAD_NOT_RUNNING error will be returned.
23324ae1
FM
1171 */
1172 wxThreadError Kill();
1173
23324ae1 1174 /**
78e87bf7
FM
1175 Suspends the thread.
1176
1177 Under some implementations (Win32), the thread is suspended immediately,
1178 under others it will only be suspended when it calls TestDestroy() for
1179 the next time (hence, if the thread doesn't call it at all, it won't be
1180 suspended).
1181
23324ae1
FM
1182 This function can only be called from another thread context.
1183 */
1184 wxThreadError Pause();
1185
1186 /**
1187 Resumes a thread suspended by the call to Pause().
78e87bf7 1188
23324ae1
FM
1189 This function can only be called from another thread context.
1190 */
1191 wxThreadError Resume();
1192
1193 /**
848f8788
FM
1194 Starts the thread execution. Should be called after Create().
1195
1196 Note that once you Run() a @b detached thread, @e any function call you do
1197 on the thread pointer (you must allocate it on the heap) is @e "unsafe";
1198 i.e. the thread may have terminated at any moment after Run() and your pointer
1199 may be dangling. See @ref thread_types for an example of safe manipulation
1200 of detached threads.
78e87bf7 1201
23324ae1 1202 This function can only be called from another thread context.
89a76d5d
FM
1203
1204 Finally, note that once a thread has completed and its Entry() function
1205 returns, you cannot call Run() on it again (an assert will fail in debug
1206 builds or @c wxTHREAD_RUNNING will be returned in release builds).
23324ae1 1207 */
4cc4bfaf 1208 wxThreadError Run();
23324ae1
FM
1209
1210 /**
78e87bf7
FM
1211 Sets the thread concurrency level for this process.
1212
1213 This is, roughly, the number of threads that the system tries to schedule
1214 to run in parallel.
4cc4bfaf 1215 The value of 0 for @a level may be used to set the default one.
78e87bf7
FM
1216
1217 @return @true on success or @false otherwise (for example, if this function is
1218 not implemented for this platform -- currently everything except Solaris).
23324ae1
FM
1219 */
1220 static bool SetConcurrency(size_t level);
1221
1222 /**
90e95e61
VZ
1223 Sets the priority of the thread, between 0 (lowest) and 100 (highest).
1224
78e87bf7 1225 It can only be set after calling Create() but before calling Run().
3c4f71cc 1226
90e95e61
VZ
1227 The following symbolic constants can be used in addition to raw
1228 values in 0..100 range:
1229 - ::wxPRIORITY_MIN: 0
1230 - ::wxPRIORITY_DEFAULT: 50
1231 - ::wxPRIORITY_MAX: 100
23324ae1 1232 */
5267aefd 1233 void SetPriority(unsigned int priority);
23324ae1
FM
1234
1235 /**
1236 Pauses the thread execution for the given amount of time.
8cd8a7fe
VZ
1237
1238 This is the same as wxMilliSleep().
23324ae1
FM
1239 */
1240 static void Sleep(unsigned long milliseconds);
1241
1242 /**
8b9aed29 1243 This function should be called periodically by the thread to ensure that
78e87bf7
FM
1244 calls to Pause() and Delete() will work.
1245
1246 If it returns @true, the thread should exit as soon as possible.
1247 Notice that under some platforms (POSIX), implementation of Pause() also
1248 relies on this function being called, so not calling it would prevent
1249 both stopping and suspending thread from working.
23324ae1
FM
1250 */
1251 virtual bool TestDestroy();
1252
1253 /**
78e87bf7
FM
1254 Return the thread object for the calling thread.
1255
1256 @NULL is returned if the calling thread is the main (GUI) thread, but
1257 IsMain() should be used to test whether the thread is really the main one
1258 because @NULL may also be returned for the thread not created with wxThread
1259 class. Generally speaking, the return value for such a thread is undefined.
23324ae1 1260 */
4cc4bfaf 1261 static wxThread* This();
23324ae1 1262
23324ae1 1263 /**
848f8788 1264 Waits for a @b joinable thread to terminate and returns the value the thread
5cba3a25
FM
1265 returned from Entry() or @c "(ExitCode)-1" on error. Notice that, unlike
1266 Delete(), this function doesn't cancel the thread in any way so the caller
1267 waits for as long as it takes to the thread to exit.
78e87bf7 1268
5cba3a25 1269 You can only Wait() for @b joinable (not detached) threads.
848f8788 1270
23324ae1 1271 This function can only be called from another thread context.
78e87bf7 1272
b95a7c31
VZ
1273 @param waitMode
1274 As described in wxThreadWait documentation, wxTHREAD_WAIT_BLOCK
1275 should be used as the wait mode even although currently
1276 wxTHREAD_WAIT_YIELD is for compatibility reasons. This parameter is
1277 new in wxWidgets 2.9.2.
1278
78e87bf7 1279 See @ref thread_deletion for a broader explanation of this routine.
23324ae1 1280 */
b95a7c31 1281 ExitCode Wait(wxThreadWait flags = wxTHREAD_WAIT_BLOCK);
23324ae1
FM
1282
1283 /**
848f8788 1284 Give the rest of the thread's time-slice to the system allowing the other
8b9aed29 1285 threads to run.
78e87bf7 1286
23324ae1 1287 Note that using this function is @b strongly discouraged, since in
78e87bf7
FM
1288 many cases it indicates a design weakness of your threading model
1289 (as does using Sleep() functions).
1290
23324ae1
FM
1291 Threads should use the CPU in an efficient manner, i.e. they should
1292 do their current work efficiently, then as soon as the work is done block
78e87bf7
FM
1293 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
1294 get signalled e.g. by other threads or a user device once further thread
1295 work is available.
1296 Using Yield() or Sleep() indicates polling-type behaviour, since we're
1297 fuzzily giving up our timeslice and wait until sometime later we'll get
1298 reactivated, at which time we realize that there isn't really much to do
1299 and Yield() again...
1300
1301 The most critical characteristic of Yield() is that it's operating system
23324ae1
FM
1302 specific: there may be scheduler changes which cause your thread to not
1303 wake up relatively soon again, but instead many seconds later,
78e87bf7
FM
1304 causing huge performance issues for your application.
1305
1306 <strong>
1307 With a well-behaving, CPU-efficient thread the operating system is likely
1308 to properly care for its reactivation the moment it needs it, whereas with
23324ae1 1309 non-deterministic, Yield-using threads all bets are off and the system
848f8788
FM
1310 scheduler is free to penalize them drastically</strong>, and this effect
1311 gets worse with increasing system load due to less free CPU resources available.
78e87bf7 1312 You may refer to various Linux kernel @c sched_yield discussions for more
23324ae1 1313 information.
78e87bf7 1314
23324ae1
FM
1315 See also Sleep().
1316 */
adaaa686 1317 static void Yield();
551266a9
FM
1318
1319protected:
1320
1321 /**
1322 This is the entry point of the thread.
1323
1324 This function is pure virtual and must be implemented by any derived class.
1325 The thread execution will start here.
1326
1327 The returned value is the thread exit code which is only useful for
1328 joinable threads and is the value returned by Wait().
1329 This function is called by wxWidgets itself and should never be called
1330 directly.
1331 */
5267aefd 1332 virtual ExitCode Entry() = 0;
551266a9
FM
1333
1334 /**
1335 This is a protected function of the wxThread class and thus can only be called
1336 from a derived class. It also can only be called in the context of this
1337 thread, i.e. a thread can only exit from itself, not from another thread.
1338
1339 This function will terminate the OS thread (i.e. stop the associated path of
1340 execution) and also delete the associated C++ object for detached threads.
1341 OnExit() will be called just before exiting.
1342 */
1343 void Exit(ExitCode exitcode = 0);
a5cc517f
FM
1344
1345private:
1346
1347 /**
1348 Called when the thread exits.
1349
1350 This function is called in the context of the thread associated with the
1351 wxThread object, not in the context of the main thread.
1352 This function will not be called if the thread was @ref Kill() killed.
1353
1354 This function should never be called directly.
1355 */
1356 virtual void OnExit();
23324ae1
FM
1357};
1358
78e87bf7
FM
1359
1360/** See wxSemaphore. */
1361enum wxSemaError
1362{
1363 wxSEMA_NO_ERROR = 0,
1364 wxSEMA_INVALID, //!< semaphore hasn't been initialized successfully
1365 wxSEMA_BUSY, //!< returned by TryWait() if Wait() would block
1366 wxSEMA_TIMEOUT, //!< returned by WaitTimeout()
1367 wxSEMA_OVERFLOW, //!< Post() would increase counter past the max
1368 wxSEMA_MISC_ERROR
1369};
1370
23324ae1
FM
1371/**
1372 @class wxSemaphore
7c913512 1373
23324ae1
FM
1374 wxSemaphore is a counter limiting the number of threads concurrently accessing
1375 a shared resource. This counter is always between 0 and the maximum value
1376 specified during the semaphore creation. When the counter is strictly greater
78e87bf7
FM
1377 than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
1378 counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
1379 block and only return when the semaphore counter becomes strictly positive
1380 again as the result of calling wxSemaphore::Post which increments the counter.
7c913512 1381
23324ae1 1382 In general, semaphores are useful to restrict access to a shared resource
78e87bf7
FM
1383 which can only be accessed by some fixed number of clients at the same time.
1384 For example, when modeling a hotel reservation system a semaphore with the counter
23324ae1 1385 equal to the total number of available rooms could be created. Each time a room
78e87bf7
FM
1386 is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
1387 and each time a room is freed it should be released by calling wxSemaphore::Post.
7c913512 1388
23324ae1 1389 @library{wxbase}
27608f11 1390 @category{threading}
23324ae1 1391*/
7c913512 1392class wxSemaphore
23324ae1
FM
1393{
1394public:
1395 /**
4cc4bfaf 1396 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
78e87bf7 1397 there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
23324ae1
FM
1398 mutex (but unlike a mutex it can be released by a thread different from the one
1399 which acquired it).
78e87bf7 1400
4cc4bfaf
FM
1401 @a initialcount is the initial value of the semaphore which must be between
1402 0 and @a maxcount (if it is not set to 0).
23324ae1
FM
1403 */
1404 wxSemaphore(int initialcount = 0, int maxcount = 0);
1405
1406 /**
1407 Destructor is not virtual, don't use this class polymorphically.
1408 */
1409 ~wxSemaphore();
1410
1411 /**
1412 Increments the semaphore count and signals one of the waiting
78e87bf7 1413 threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
23324ae1 1414 would increase the counter past the maximum.
3c4f71cc 1415
d29a9a8a 1416 @return One of:
78e87bf7
FM
1417 - wxSEMA_NO_ERROR: There was no error.
1418 - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
1419 - wxSEMA_OVERFLOW: Post() would increase counter past the max.
1420 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1421 */
1422 wxSemaError Post();
1423
1424 /**
1425 Same as Wait(), but returns immediately.
3c4f71cc 1426
d29a9a8a 1427 @return One of:
78e87bf7
FM
1428 - wxSEMA_NO_ERROR: There was no error.
1429 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1430 - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
1431 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1432 */
1433 wxSemaError TryWait();
1434
1435 /**
1436 Wait indefinitely until the semaphore count becomes strictly positive
1437 and then decrement it and return.
3c4f71cc 1438
d29a9a8a 1439 @return One of:
78e87bf7
FM
1440 - wxSEMA_NO_ERROR: There was no error.
1441 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1442 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1443 */
1444 wxSemaError Wait();
78e87bf7
FM
1445
1446 /**
1447 Same as Wait(), but with a timeout limit.
1448
1449 @return One of:
1450 - wxSEMA_NO_ERROR: There was no error.
1451 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1452 - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
1453 - wxSEMA_MISC_ERROR: Miscellaneous error.
1454 */
5267aefd 1455 wxSemaError WaitTimeout(unsigned long timeout_millis);
23324ae1
FM
1456};
1457
1458
e54c96f1 1459
23324ae1
FM
1460/**
1461 @class wxMutexLocker
7c913512 1462
78e87bf7
FM
1463 This is a small helper class to be used with wxMutex objects.
1464
1465 A wxMutexLocker acquires a mutex lock in the constructor and releases
23324ae1
FM
1466 (or unlocks) the mutex in the destructor making it much more difficult to
1467 forget to release a mutex (which, in general, will promptly lead to serious
78e87bf7 1468 problems). See wxMutex for an example of wxMutexLocker usage.
7c913512 1469
23324ae1 1470 @library{wxbase}
27608f11 1471 @category{threading}
7c913512 1472
e54c96f1 1473 @see wxMutex, wxCriticalSectionLocker
23324ae1 1474*/
7c913512 1475class wxMutexLocker
23324ae1
FM
1476{
1477public:
1478 /**
1479 Constructs a wxMutexLocker object associated with mutex and locks it.
0dd88987 1480 Call IsOk() to check if the mutex was successfully locked.
23324ae1
FM
1481 */
1482 wxMutexLocker(wxMutex& mutex);
1483
1484 /**
1485 Destructor releases the mutex if it was successfully acquired in the ctor.
1486 */
1487 ~wxMutexLocker();
1488
1489 /**
1490 Returns @true if mutex was acquired in the constructor, @false otherwise.
1491 */
328f5751 1492 bool IsOk() const;
23324ae1
FM
1493};
1494
1495
3ad41c28
RR
1496/**
1497 The possible wxMutex kinds.
1498*/
1499enum wxMutexType
1500{
424c9ce7 1501 /** Normal non-recursive mutex: try to always use this one. */
78e87bf7 1502 wxMUTEX_DEFAULT,
3ad41c28 1503
9c5313d1 1504 /** Recursive mutex: don't use these ones with wxCondition. */
78e87bf7 1505 wxMUTEX_RECURSIVE
3ad41c28
RR
1506};
1507
1508
1509/**
1510 The possible wxMutex errors.
1511*/
1512enum wxMutexError
1513{
9c5313d1 1514 /** The operation completed successfully. */
78e87bf7
FM
1515 wxMUTEX_NO_ERROR = 0,
1516
9c5313d1 1517 /** The mutex hasn't been initialized. */
78e87bf7
FM
1518 wxMUTEX_INVALID,
1519
1520 /** The mutex is already locked by the calling thread. */
1521 wxMUTEX_DEAD_LOCK,
1522
9c5313d1 1523 /** The mutex is already locked by another thread. */
78e87bf7
FM
1524 wxMUTEX_BUSY,
1525
9c5313d1 1526 /** An attempt to unlock a mutex which is not locked. */
78e87bf7
FM
1527 wxMUTEX_UNLOCKED,
1528
9c5313d1 1529 /** wxMutex::LockTimeout() has timed out. */
78e87bf7
FM
1530 wxMUTEX_TIMEOUT,
1531
9c5313d1 1532 /** Any other error */
78e87bf7 1533 wxMUTEX_MISC_ERROR
3ad41c28
RR
1534};
1535
1536
23324ae1
FM
1537/**
1538 @class wxMutex
7c913512 1539
23324ae1
FM
1540 A mutex object is a synchronization object whose state is set to signaled when
1541 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
1542 from its usefulness in coordinating mutually-exclusive access to a shared
1543 resource as only one thread at a time can own a mutex object.
7c913512 1544
23324ae1
FM
1545 Mutexes may be recursive in the sense that a thread can lock a mutex which it
1546 had already locked before (instead of dead locking the entire process in this
1547 situation by starting to wait on a mutex which will never be released while the
7c913512 1548 thread is waiting) but using them is not recommended under Unix and they are
424c9ce7 1549 @b not recursive by default. The reason for this is that recursive
23324ae1 1550 mutexes are not supported by all Unix flavours and, worse, they cannot be used
424c9ce7 1551 with wxCondition.
7c913512 1552
23324ae1
FM
1553 For example, when several threads use the data stored in the linked list,
1554 modifications to the list should only be allowed to one thread at a time
1555 because during a new node addition the list integrity is temporarily broken
5cba3a25 1556 (this is also called @e program @e invariant).
7c913512 1557
3ad41c28
RR
1558 @code
1559 // this variable has an "s_" prefix because it is static: seeing an "s_" in
1560 // a multithreaded program is in general a good sign that you should use a
1561 // mutex (or a critical section)
1562 static wxMutex *s_mutexProtectingTheGlobalData;
1563
1564 // we store some numbers in this global array which is presumably used by
1565 // several threads simultaneously
1566 wxArrayInt s_data;
1567
1568 void MyThread::AddNewNode(int num)
1569 {
1570 // ensure that no other thread accesses the list
1571 s_mutexProtectingTheGlobalList->Lock();
1572
1573 s_data.Add(num);
1574
1575 s_mutexProtectingTheGlobalList->Unlock();
1576 }
1577
1578 // return true if the given number is greater than all array elements
1579 bool MyThread::IsGreater(int num)
1580 {
1581 // before using the list we must acquire the mutex
1582 wxMutexLocker lock(s_mutexProtectingTheGlobalData);
1583
1584 size_t count = s_data.Count();
1585 for ( size_t n = 0; n < count; n++ )
1586 {
1587 if ( s_data[n] > num )
1588 return false;
1589 }
1590
1591 return true;
1592 }
1593 @endcode
1594
1595 Notice how wxMutexLocker was used in the second function to ensure that the
1596 mutex is unlocked in any case: whether the function returns true or false
5cba3a25
FM
1597 (because the destructor of the local object @e lock is always called).
1598 Using this class instead of directly using wxMutex is, in general, safer
1599 and is even more so if your program uses C++ exceptions.
3ad41c28 1600
23324ae1 1601 @library{wxbase}
27608f11 1602 @category{threading}
7c913512 1603
e54c96f1 1604 @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
23324ae1 1605*/
7c913512 1606class wxMutex
23324ae1
FM
1607{
1608public:
1609 /**
1610 Default constructor.
1611 */
1612 wxMutex(wxMutexType type = wxMUTEX_DEFAULT);
1613
1614 /**
1615 Destroys the wxMutex object.
1616 */
1617 ~wxMutex();
1618
1619 /**
78e87bf7
FM
1620 Locks the mutex object.
1621 This is equivalent to LockTimeout() with infinite timeout.
3c4f71cc 1622
db034c52
FM
1623 Note that if this mutex is already locked by the caller thread,
1624 this function doesn't block but rather immediately returns.
1625
0dd88987 1626 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
23324ae1
FM
1627 */
1628 wxMutexError Lock();
1629
1630 /**
1631 Try to lock the mutex object during the specified time interval.
3c4f71cc 1632
0dd88987 1633 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
23324ae1
FM
1634 */
1635 wxMutexError LockTimeout(unsigned long msec);
1636
1637 /**
1638 Tries to lock the mutex object. If it can't, returns immediately with an error.
3c4f71cc 1639
0dd88987 1640 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
23324ae1
FM
1641 */
1642 wxMutexError TryLock();
1643
1644 /**
1645 Unlocks the mutex object.
3c4f71cc 1646
0dd88987 1647 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
23324ae1
FM
1648 */
1649 wxMutexError Unlock();
1650};
1651
1652
e54c96f1 1653
23324ae1
FM
1654// ============================================================================
1655// Global functions/macros
1656// ============================================================================
1657
b21126db 1658/** @addtogroup group_funcmacro_thread */
3950d49c
BP
1659//@{
1660
23324ae1 1661/**
3950d49c
BP
1662 This macro declares a (static) critical section object named @a cs if
1663 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1664
1665 @header{wx/thread.h}
23324ae1 1666*/
3950d49c
BP
1667#define wxCRIT_SECT_DECLARE(cs)
1668
1669/**
1670 This macro declares a critical section object named @a cs if
1671 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
1672 the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
1673 declare a class or struct member which explains its name.
1674
1675 @header{wx/thread.h}
1676*/
1677#define wxCRIT_SECT_DECLARE_MEMBER(cs)
23324ae1
FM
1678
1679/**
3950d49c
BP
1680 This macro creates a wxCriticalSectionLocker named @a name and associated
1681 with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
1682 if it is 0.
1683
1684 @header{wx/thread.h}
1685*/
1686#define wxCRIT_SECT_LOCKER(name, cs)
1687
1688/**
1689 This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
1690 creates a static critical section object and also the lock object
1691 associated with it. Because of this, it can be only used inside a function,
1692 not at global scope. For example:
4cc4bfaf 1693
23324ae1
FM
1694 @code
1695 int IncCount()
1696 {
1697 static int s_counter = 0;
7c913512 1698
23324ae1 1699 wxCRITICAL_SECTION(counter);
7c913512 1700
23324ae1
FM
1701 return ++s_counter;
1702 }
1703 @endcode
7c913512 1704
3950d49c
BP
1705 Note that this example assumes that the function is called the first time
1706 from the main thread so that the critical section object is initialized
1707 correctly by the time other threads start calling it, if this is not the
1708 case this approach can @b not be used and the critical section must be made
1709 a global instead.
1710
1711 @header{wx/thread.h}
23324ae1 1712*/
3950d49c 1713#define wxCRITICAL_SECTION(name)
23324ae1
FM
1714
1715/**
3950d49c
BP
1716 This macro is equivalent to
1717 @ref wxCriticalSection::Leave "critical_section.Leave()" if
1718 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1719
1720 @header{wx/thread.h}
1721*/
1722#define wxLEAVE_CRIT_SECT(critical_section)
1723
1724/**
1725 This macro is equivalent to
1726 @ref wxCriticalSection::Enter "critical_section.Enter()" if
1727 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1728
1729 @header{wx/thread.h}
1730*/
1731#define wxENTER_CRIT_SECT(critical_section)
1732
1733/**
1734 Returns @true if this thread is the main one. Always returns @true if
1735 @c wxUSE_THREADS is 0.
1736
1737 @header{wx/thread.h}
23324ae1 1738*/
3950d49c 1739bool wxIsMainThread();
23324ae1 1740
ae93dddf
FM
1741
1742
23324ae1
FM
1743/**
1744 This function must be called when any thread other than the main GUI thread
3950d49c
BP
1745 wants to get access to the GUI library. This function will block the
1746 execution of the calling thread until the main thread (or any other thread
1747 holding the main GUI lock) leaves the GUI library and no other thread will
1748 enter the GUI library until the calling thread calls wxMutexGuiLeave().
1749
23324ae1 1750 Typically, these functions are used like this:
4cc4bfaf 1751
23324ae1
FM
1752 @code
1753 void MyThread::Foo(void)
1754 {
3950d49c
BP
1755 // before doing any GUI calls we must ensure that
1756 // this thread is the only one doing it!
7c913512 1757
23324ae1 1758 wxMutexGuiEnter();
7c913512 1759
23324ae1 1760 // Call GUI here:
c6427d4d 1761 my_window->DrawSomething();
7c913512 1762
23324ae1
FM
1763 wxMutexGuiLeave();
1764 }
1765 @endcode
7c913512 1766
23324ae1 1767 This function is only defined on platforms which support preemptive
ae93dddf 1768 threads and only works under some ports (wxMSW currently).
3950d49c
BP
1769
1770 @note Under GTK, no creation of top-level windows is allowed in any thread
1771 but the main one.
1772
1773 @header{wx/thread.h}
23324ae1
FM
1774*/
1775void wxMutexGuiEnter();
1776
1777/**
3950d49c
BP
1778 This function is only defined on platforms which support preemptive
1779 threads.
23324ae1 1780
3950d49c 1781 @see wxMutexGuiEnter()
23324ae1 1782
3950d49c 1783 @header{wx/thread.h}
23324ae1 1784*/
3950d49c 1785void wxMutexGuiLeave();
23324ae1 1786
3950d49c 1787//@}
23324ae1 1788