]> git.saurik.com Git - wxWidgets.git/blame - interface/wx/thread.h
don't duplicate SetInitialSocketBuffers()
[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$
6// Licence: wxWindows license
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
282 class MyFrame : public wxFrame, public wxThreadHelper
283 {
284 public:
285 MyFrame() : wxThreadHelper(wxTHREAD_JOINABLE) {}
286
287 ...
288
289 virtual ExitCode Entry()
290 {
291 // here we do our long task, periodically calling TestDestroy():
292 while (!TestDestroy())
293 {
294 // ...do another bit of work here...
295
296 // post an update message to the frame
297 }
298
299 // TestDestroy() returned true (which means the main thread
300 // asked us to terminate as soon as possible) or we ended the
301 // long task...
302 return (ExitCode)0;
303 }
304
305 ~MyFrame()
306 {
307 // important: before terminating, we _must_ wait for our
308 // joinable thread to end, if it's running!
309 if (GetThread()->IsRunning())
310 GetThread()->Wait();
311 }
312
313 ...
314 void DoStartALongTask();
315 ...
316 }
317
318 void MyFrame::DoStartALongTask()
319 {
320 // we want to start a long task, but we don't want our GUI to block
321 // while it's executed, so we use a thread to do it.
322 if (Create() != wxTHREAD_NO_ERROR)
323 {
324 wxLogError("Could not create the worker thread!");
325 return;
326 }
327
328 // go!
329 if (Run() != wxTHREAD_NO_ERROR)
330 {
331 wxLogError("Could not run the worker thread!");
332 return;
333 }
334 }
335 @endcode
336
23324ae1 337 @library{wxbase}
27608f11 338 @category{threading}
7c913512 339
e54c96f1 340 @see wxThread
23324ae1 341*/
7c913512 342class wxThreadHelper
23324ae1
FM
343{
344public:
345 /**
5cba3a25
FM
346 This constructor simply initializes internal member variables and tells
347 wxThreadHelper which type the thread internally managed should be.
23324ae1 348 */
4ccf0566 349 wxThreadHelper(wxThreadKind kind = wxTHREAD_JOINABLE);
23324ae1
FM
350
351 /**
5cba3a25
FM
352 The destructor frees the resources associated with the thread, forcing
353 it to terminate (it uses wxThread::Kill function).
354
355 Because of the wxThread::Kill unsafety, you should always wait
356 (with wxThread::Wait) for joinable threads to end or call wxThread::Delete
357 on detached threads, instead of relying on this destructor for stopping
358 the thread.
23324ae1 359 */
adaaa686 360 virtual ~wxThreadHelper();
23324ae1 361
23324ae1 362 /**
78e87bf7
FM
363 This is the entry point of the thread.
364
365 This function is pure virtual and must be implemented by any derived class.
366 The thread execution will start here.
367
23324ae1 368 The returned value is the thread exit code which is only useful for
78e87bf7
FM
369 joinable threads and is the value returned by @c "GetThread()->Wait()".
370
23324ae1
FM
371 This function is called by wxWidgets itself and should never be called
372 directly.
373 */
5267aefd 374 virtual ExitCode Entry() = 0;
23324ae1 375
551266a9
FM
376 /**
377 Creates a new thread.
378
379 The thread object is created in the suspended state, and you
5cba3a25 380 should call @ref wxThread::Run "GetThread()->Run()" to start running it.
551266a9
FM
381
382 You may optionally specify the stack size to be allocated to it (ignored
383 on platforms that don't support setting it explicitly, eg. Unix).
384
5cba3a25
FM
385 Note that the type of the thread which is created is defined in the
386 constructor.
387
551266a9
FM
388 @return One of the ::wxThreadError enum values.
389 */
390 wxThreadError Create(unsigned int stackSize = 0);
391
23324ae1 392 /**
5cba3a25
FM
393 This is a public function that returns the wxThread object associated with
394 the thread.
23324ae1 395 */
adaaa686 396 wxThread* GetThread() const;
23324ae1
FM
397};
398
3ad41c28
RR
399/**
400 Possible critical section types
401*/
23324ae1 402
3ad41c28
RR
403enum wxCriticalSectionType
404{
405 wxCRITSEC_DEFAULT,
406 /** Recursive critical section under both Windows and Unix */
407
78e87bf7 408 wxCRITSEC_NON_RECURSIVE
3ad41c28
RR
409 /** Non-recursive critical section under Unix, recursive under Windows */
410};
e54c96f1 411
23324ae1
FM
412/**
413 @class wxCriticalSection
7c913512 414
78e87bf7
FM
415 A critical section object is used for exactly the same purpose as a wxMutex.
416 The only difference is that under Windows platform critical sections are only
417 visible inside one process, while mutexes may be shared among processes,
418 so using critical sections is slightly more efficient.
419
420 The terminology is also slightly different: mutex may be locked (or acquired)
421 and unlocked (or released) while critical section is entered and left by the program.
7c913512 422
3ad41c28 423 Finally, you should try to use wxCriticalSectionLocker class whenever
7c913512 424 possible instead of directly using wxCriticalSection for the same reasons
3ad41c28 425 wxMutexLocker is preferrable to wxMutex - please see wxMutex for an example.
7c913512 426
23324ae1 427 @library{wxbase}
27608f11 428 @category{threading}
7c913512 429
e54c96f1 430 @see wxThread, wxCondition, wxCriticalSectionLocker
23324ae1 431*/
7c913512 432class wxCriticalSection
23324ae1
FM
433{
434public:
435 /**
78e87bf7
FM
436 Default constructor initializes critical section object.
437 By default critical sections are recursive under Unix and Windows.
23324ae1 438 */
3ad41c28 439 wxCriticalSection( wxCriticalSectionType critSecType = wxCRITSEC_DEFAULT );
23324ae1
FM
440
441 /**
442 Destructor frees the resources.
443 */
444 ~wxCriticalSection();
445
446 /**
78e87bf7
FM
447 Enter the critical section (same as locking a mutex).
448
449 There is no error return for this function.
450 After entering the critical section protecting some global
23324ae1
FM
451 data the thread running in critical section may safely use/modify it.
452 */
453 void Enter();
454
455 /**
78e87bf7
FM
456 Leave the critical section allowing other threads use the global data
457 protected by it. There is no error return for this function.
23324ae1
FM
458 */
459 void Leave();
460};
461
3ad41c28
RR
462/**
463 The possible thread kinds.
464*/
465enum wxThreadKind
466{
9c5313d1 467 /** Detached thread */
78e87bf7
FM
468 wxTHREAD_DETACHED,
469
9c5313d1 470 /** Joinable thread */
78e87bf7 471 wxTHREAD_JOINABLE
3ad41c28
RR
472};
473
474/**
475 The possible thread errors.
476*/
477enum wxThreadError
478{
9c5313d1 479 /** No error */
78e87bf7
FM
480 wxTHREAD_NO_ERROR = 0,
481
9c5313d1 482 /** No resource left to create a new thread. */
78e87bf7
FM
483 wxTHREAD_NO_RESOURCE,
484
9c5313d1 485 /** The thread is already running. */
78e87bf7
FM
486 wxTHREAD_RUNNING,
487
488 /** The thread isn't running. */
489 wxTHREAD_NOT_RUNNING,
490
9c5313d1 491 /** Thread we waited for had to be killed. */
78e87bf7
FM
492 wxTHREAD_KILLED,
493
9c5313d1 494 /** Some other error */
78e87bf7 495 wxTHREAD_MISC_ERROR
3ad41c28
RR
496};
497
498/**
499 Defines the interval of priority
500*/
501enum
502{
503 WXTHREAD_MIN_PRIORITY = 0u,
504 WXTHREAD_DEFAULT_PRIORITY = 50u,
505 WXTHREAD_MAX_PRIORITY = 100u
506};
23324ae1 507
e54c96f1 508
23324ae1
FM
509/**
510 @class wxThread
7c913512 511
78e87bf7
FM
512 A thread is basically a path of execution through a program.
513 Threads are sometimes called @e light-weight processes, but the fundamental difference
23324ae1 514 between threads and processes is that memory spaces of different processes are
7c913512
FM
515 separated while all threads share the same address space.
516
23324ae1 517 While it makes it much easier to share common data between several threads, it
bb3e5526 518 also makes it much easier to shoot oneself in the foot, so careful use of
5cba3a25
FM
519 synchronization objects such as mutexes (see wxMutex) or critical sections
520 (see wxCriticalSection) is recommended.
521 In addition, don't create global thread objects because they allocate memory
522 in their constructor, which will cause problems for the memory checking system.
523
78e87bf7
FM
524
525 @section thread_types Types of wxThreads
526
527 There are two types of threads in wxWidgets: @e detached and @e joinable,
528 modeled after the the POSIX thread API. This is different from the Win32 API
529 where all threads are joinable.
530
5cba3a25
FM
531 By default wxThreads in wxWidgets use the @b detached behavior.
532 Detached threads delete themselves once they have completed, either by themselves
533 when they complete processing or through a call to Delete(), and thus
534 @b must be created on the heap (through the new operator, for example).
535
536 Typically you'll want to store the instances of the detached wxThreads you
537 allocate, so that you can call functions on them.
538 Because of their nature however you'll need to always use a critical section
539 when accessing them:
540
541 @code
542 // declare a new type of event, to be used by our MyThread class:
543 extern const wxEventType wxEVT_COMMAND_MYTHREAD_COMPLETED;
544
545 class MyThread : public wxThread
546 {
547 public:
548 MyThread(wxEvtHandler *handler) : wxThread(wxTHREAD_DETACHED)
549 { m_pHandler = handler; }
550
551 ExitCode Entry()
552 {
553 while (!TestDestroy())
554 {
555 // ... do a bit of work...
556 }
557
558 // signal the event handler that this thread is going to be destroyed
559 // NOTE: here we assume that using the m_pHandler pointer is safe,
560 // (in this case it's assured by the MyFrame destructor)
561 wxQueueEvent(m_pHandler, new wxCommandEvent(wxEVT_COMMAND_MYTHREAD_COMPLETED));
562
563 return (ExitCode)0; // success
564 }
565
566 wxEvtHandler *m_pHandler;
567 };
568
569 class MyFrame : public wxFrame
570 {
571 public:
572 ...
573 ~MyFrame();
574 ...
575 void DoStartThread();
576 void DoPauseThread();
577
578 // a resume routine would be mostly identic to DoPauseThread()
579 void DoResumeThread() { ... }
580
581 void OnThreadExit(wxCommandEvent&);
582
583 protected:
584 MyThread *m_pThread;
585
586 // this is _required_ for writing safe code!
587 wxCriticalSection m_critSection;
588 };
589
590 void MyFrame::DoStartThread()
591 {
592 m_pThread = new wxThread();
593
594 if ( m_pThread->Create() != wxTHREAD_NO_ERROR )
595 {
596 wxLogError("Can't create the thread!");
597 delete m_pThread;
598 m_pThread = NULL;
599 }
600 else
601 {
602 if (m_pThread->Run() != wxTHREAD_NO_ERROR )
603 {
604 wxLogError("Can't create the thread!");
605 delete m_pThread;
606 m_pThread = NULL;
607 }
608
609 // after the call to wxThread::Run(), the m_pThread pointer is "unsafe":
610 // at any moment the thread may cease to exist (because it completes its work).
611 // To avoid dangling pointers OnThreadExit() will set m_pThread
612 // to NULL when the thread dies.
613 }
614 }
615
616 void MyFrame::OnThreadExit(wxCommandEvent&)
617 {
618 // the thread just ended; make sure not to leave dangling pointers around
619 m_pThread = NULL;
620 }
621
622 void MyFrame::DoPauseThread()
623 {
624 // anytime we access the m_pThread pointer we must ensure that it won't
625 // be modified in the meanwhile; inside a critical section we are sure
626 // that we are the only thread running, so that's what we need.
627 wxCriticalSectionLocker enter(m_critSection);
628
629 if (m_pThread) // does the thread still exist?
630 {
631 // without a critical section, once reached this point it may happen
632 // that the OS scheduler gives control to the MyThread::Entry() function,
633 // which in turn may return (because it completes its work) making
634 // invalid the m_pThread pointer; the critical section above
635 // makes this code safe.
636
637 if (m_pThread->Pause() != wxTHREAD_NO_ERROR )
638 wxLogError("Can't pause the thread!");
639 }
640 }
641
642 MyFrame::~MyFrame()
643 {
644 wxCriticalSectionLocker enter(m_critSection);
645
646 if (m_pThread) // does the thread still exist?
647 {
648 if (m_pThread->Delete() != wxTHREAD_NO_ERROR )
649 wxLogError("Can't delete the thread!");
650
651 // as soon as we exit the critical section and the MyThread::Entry
652 // function calls TestDestroy(), the thread will exit and thus
653 // call OnExitThread(); we need to maintain MyFrame object alive
654 // until then:
655 wxEventLoopBase* p = wxEventLoopBase::GetActive();
656 while (p->Pending() && m_pThread)
657 p->Dispatch();
658
659 // the wxEVT_COMMAND_MYTHREAD_COMPLETED event was posted, we can
660 // safely exit
661 }
662 }
663 @endcode
664
665 Conversely, @b joinable threads do not delete themselves when they are done
78e87bf7
FM
666 processing and as such are safe to create on the stack. Joinable threads
667 also provide the ability for one to get value it returned from Entry()
668 through Wait().
78e87bf7
FM
669 You shouldn't hurry to create all the threads joinable, however, because this
670 has a disadvantage as well: you @b must Wait() for a joinable thread or the
671 system resources used by it will never be freed, and you also must delete the
672 corresponding wxThread object yourself if you did not create it on the stack.
5cba3a25
FM
673 In contrast, detached threads are of the "fire-and-forget" kind: you only have
674 to start a detached thread and it will terminate and destroy itself.
78e87bf7
FM
675
676
677 @section thread_deletion wxThread Deletion
678
679 Regardless of whether it has terminated or not, you should call Wait() on a
5cba3a25 680 @b joinable thread to release its memory, as outlined in @ref thread_types.
78e87bf7
FM
681 If you created a joinable thread on the heap, remember to delete it manually
682 with the @c delete operator or similar means as only detached threads handle
683 this type of memory management.
684
5cba3a25 685 Since @b detached threads delete themselves when they are finished processing,
78e87bf7
FM
686 you should take care when calling a routine on one. If you are certain the
687 thread is still running and would like to end it, you may call Delete()
688 to gracefully end it (which implies that the thread will be deleted after
5cba3a25
FM
689 that call to Delete()). It should be implied that you should @b never attempt
690 to delete a detached thread with the @c delete operator or similar means.
691
692 As mentioned, Wait() or Delete() functions attempt to gracefully terminate a
693 joinable and a detached thread, respectively. They do this by waiting until
694 the thread in question calls TestDestroy() or ends processing (i.e. returns
78e87bf7
FM
695 from wxThread::Entry).
696
5cba3a25
FM
697 Obviously, if the thread does call TestDestroy() and does not end, the
698 thread which called Wait() or Delete() will come to halt.
699 This is why it's important to call TestDestroy() in the Entry() routine of
700 your threads as often as possible and immediately exit when it returns @true.
701
78e87bf7
FM
702 As a last resort you can end the thread immediately through Kill(). It is
703 strongly recommended that you do not do this, however, as it does not free
704 the resources associated with the object (although the wxThread object of
705 detached threads will still be deleted) and could leave the C runtime
706 library in an undefined state.
707
708
709 @section thread_secondary wxWidgets Calls in Secondary Threads
710
5cba3a25
FM
711 All threads other than the "main application thread" (the one running
712 wxApp::OnInit() or the one your main function runs in, for example) are
713 considered "secondary threads". These include all threads created by Create()
714 or the corresponding constructors.
78e87bf7
FM
715
716 GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe
717 at all in secondary threads and could end your application prematurely.
718 This is due to several reasons, including the underlying native API and
719 the fact that wxThread does not run a GUI event loop similar to other APIs
720 as MFC.
721
722 A workaround for some wxWidgets ports is calling wxMutexGUIEnter()
723 before any GUI calls and then calling wxMutexGUILeave() afterwords. However,
724 the recommended way is to simply process the GUI calls in the main thread
5cba3a25 725 through an event that is posted by wxQueueEvent().
78e87bf7
FM
726 This does not imply that calls to these classes are thread-safe, however,
727 as most wxWidgets classes are not thread-safe, including wxString.
728
729
730 @section thread_poll Don't Poll a wxThread
731
732 A common problem users experience with wxThread is that in their main thread
733 they will check the thread every now and then to see if it has ended through
734 IsRunning(), only to find that their application has run into problems
5cba3a25
FM
735 because the thread is using the default behavior (i.e. it's @b detached) and
736 has already deleted itself.
737 Naturally, they instead attempt to use joinable threads in place of the previous
738 behavior. However, polling a wxThread for when it has ended is in general a
739 bad idea - in fact calling a routine on any running wxThread should be avoided
740 if possible. Instead, find a way to notify yourself when the thread has ended.
78e87bf7
FM
741
742 Usually you only need to notify the main thread, in which case you can
5cba3a25 743 post an event to it via wxQueueEvent().
78e87bf7
FM
744 In the case of secondary threads you can call a routine of another class
745 when the thread is about to complete processing and/or set the value of
746 a variable, possibly using mutexes (see wxMutex) and/or other synchronization
747 means if necessary.
bb3e5526 748
23324ae1 749 @library{wxbase}
27608f11 750 @category{threading}
78e87bf7 751
5cba3a25
FM
752 @see wxThreadHelper, wxMutex, wxCondition, wxCriticalSection,
753 @ref overview_thread
23324ae1 754*/
7c913512 755class wxThread
23324ae1
FM
756{
757public:
5cba3a25
FM
758 /**
759 The return type for the thread functions.
760 */
761 typedef void* ExitCode;
762
23324ae1 763 /**
8b9aed29 764 This constructor creates a new detached (default) or joinable C++
78e87bf7 765 thread object. It does not create or start execution of the real thread -
8b9aed29 766 for this you should use the Create() and Run() methods.
78e87bf7 767
4cc4bfaf 768 The possible values for @a kind parameters are:
8b9aed29
RR
769 - @b wxTHREAD_DETACHED - Creates a detached thread.
770 - @b wxTHREAD_JOINABLE - Creates a joinable thread.
23324ae1
FM
771 */
772 wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
773
774 /**
78e87bf7
FM
775 The destructor frees the resources associated with the thread.
776 Notice that you should never delete a detached thread -- you may only call
777 Delete() on it or wait until it terminates (and auto destructs) itself.
778
779 Because the detached threads delete themselves, they can only be allocated on the heap.
23324ae1 780 Joinable threads should be deleted explicitly. The Delete() and Kill() functions
78e87bf7 781 will not delete the C++ thread object. It is also safe to allocate them on stack.
23324ae1 782 */
adaaa686 783 virtual ~wxThread();
23324ae1
FM
784
785 /**
78e87bf7
FM
786 Creates a new thread.
787
788 The thread object is created in the suspended state, and you should call Run()
789 to start running it. You may optionally specify the stack size to be allocated
790 to it (Ignored on platforms that don't support setting it explicitly,
791 eg. Unix system without @c pthread_attr_setstacksize).
792
793 If you do not specify the stack size,the system's default value is used.
794
795 @warning
796 It is a good idea to explicitly specify a value as systems'
797 default values vary from just a couple of KB on some systems (BSD and
798 OS/2 systems) to one or several MB (Windows, Solaris, Linux).
799 So, if you have a thread that requires more than just a few KB of memory, you
800 will have mysterious problems on some platforms but not on the common ones.
801 On the other hand, just indicating a large stack size by default will give you
802 performance issues on those systems with small default stack since those
803 typically use fully committed memory for the stack.
804 On the contrary, if you use a lot of threads (say several hundred),
805 virtual adress space can get tight unless you explicitly specify a
806 smaller amount of thread stack space for each thread.
3c4f71cc 807
d29a9a8a 808 @return One of:
8b9aed29
RR
809 - @b wxTHREAD_NO_ERROR - No error.
810 - @b wxTHREAD_NO_RESOURCE - There were insufficient resources to create the thread.
811 - @b wxTHREAD_NO_RUNNING - The thread is already running
23324ae1
FM
812 */
813 wxThreadError Create(unsigned int stackSize = 0);
814
815 /**
5cba3a25
FM
816 Calling Delete() gracefully terminates a @b detached thread, either when
817 the thread calls TestDestroy() or when it finishes processing.
78e87bf7
FM
818
819 @note
820 While this could work on a joinable thread you simply should not
5cba3a25
FM
821 call this routine on them as afterwards you may not be able to call
822 Wait() to free the memory of that thread.
78e87bf7
FM
823
824 See @ref thread_deletion for a broader explanation of this routine.
23324ae1 825 */
5267aefd 826 wxThreadError Delete(void** rc = NULL);
23324ae1 827
23324ae1
FM
828 /**
829 Returns the number of system CPUs or -1 if the value is unknown.
3c4f71cc 830
4cc4bfaf 831 @see SetConcurrency()
23324ae1
FM
832 */
833 static int GetCPUCount();
834
835 /**
78e87bf7
FM
836 Returns the platform specific thread ID of the current thread as a long.
837 This can be used to uniquely identify threads, even if they are not wxThreads.
23324ae1
FM
838 */
839 static unsigned long GetCurrentId();
840
841 /**
842 Gets the thread identifier: this is a platform dependent number that uniquely
78e87bf7
FM
843 identifies the thread throughout the system during its existence
844 (i.e. the thread identifiers may be reused).
23324ae1 845 */
5267aefd 846 wxThreadIdType GetId() const;
23324ae1
FM
847
848 /**
849 Gets the priority of the thread, between zero and 100.
78e87bf7 850
23324ae1 851 The following priorities are defined:
8b9aed29
RR
852 - @b WXTHREAD_MIN_PRIORITY: 0
853 - @b WXTHREAD_DEFAULT_PRIORITY: 50
854 - @b WXTHREAD_MAX_PRIORITY: 100
23324ae1 855 */
5267aefd 856 unsigned int GetPriority() const;
23324ae1
FM
857
858 /**
859 Returns @true if the thread is alive (i.e. started and not terminating).
78e87bf7 860
23324ae1
FM
861 Note that this function can only safely be used with joinable threads, not
862 detached ones as the latter delete themselves and so when the real thread is
863 no longer alive, it is not possible to call this function because
864 the wxThread object no longer exists.
865 */
328f5751 866 bool IsAlive() const;
23324ae1
FM
867
868 /**
869 Returns @true if the thread is of the detached kind, @false if it is a
78e87bf7 870 joinable one.
23324ae1 871 */
328f5751 872 bool IsDetached() const;
23324ae1
FM
873
874 /**
875 Returns @true if the calling thread is the main application thread.
876 */
877 static bool IsMain();
878
879 /**
880 Returns @true if the thread is paused.
881 */
328f5751 882 bool IsPaused() const;
23324ae1
FM
883
884 /**
885 Returns @true if the thread is running.
78e87bf7 886
7c913512 887 This method may only be safely used for joinable threads, see the remark in
23324ae1
FM
888 IsAlive().
889 */
328f5751 890 bool IsRunning() const;
23324ae1
FM
891
892 /**
78e87bf7
FM
893 Immediately terminates the target thread.
894
895 @b "This function is dangerous and should be used with extreme care"
896 (and not used at all whenever possible)! The resources allocated to the
897 thread will not be freed and the state of the C runtime library may become
898 inconsistent. Use Delete() for detached threads or Wait() for joinable
899 threads instead.
900
23324ae1
FM
901 For detached threads Kill() will also delete the associated C++ object.
902 However this will not happen for joinable threads and this means that you will
903 still have to delete the wxThread object yourself to avoid memory leaks.
78e87bf7
FM
904
905 In neither case OnExit() of the dying thread will be called, so no
906 thread-specific cleanup will be performed.
23324ae1
FM
907 This function can only be called from another thread context, i.e. a thread
908 cannot kill itself.
78e87bf7 909
23324ae1
FM
910 It is also an error to call this function for a thread which is not running or
911 paused (in the latter case, the thread will be resumed first) -- if you do it,
8b9aed29 912 a @b wxTHREAD_NOT_RUNNING error will be returned.
23324ae1
FM
913 */
914 wxThreadError Kill();
915
916 /**
78e87bf7
FM
917 Called when the thread exits.
918
919 This function is called in the context of the thread associated with the
920 wxThread object, not in the context of the main thread.
921 This function will not be called if the thread was @ref Kill() killed.
922
23324ae1
FM
923 This function should never be called directly.
924 */
adaaa686 925 virtual void OnExit();
23324ae1
FM
926
927 /**
78e87bf7
FM
928 Suspends the thread.
929
930 Under some implementations (Win32), the thread is suspended immediately,
931 under others it will only be suspended when it calls TestDestroy() for
932 the next time (hence, if the thread doesn't call it at all, it won't be
933 suspended).
934
23324ae1
FM
935 This function can only be called from another thread context.
936 */
937 wxThreadError Pause();
938
939 /**
940 Resumes a thread suspended by the call to Pause().
78e87bf7 941
23324ae1
FM
942 This function can only be called from another thread context.
943 */
944 wxThreadError Resume();
945
946 /**
947 Starts the thread execution. Should be called after
948 Create().
78e87bf7 949
23324ae1
FM
950 This function can only be called from another thread context.
951 */
4cc4bfaf 952 wxThreadError Run();
23324ae1
FM
953
954 /**
78e87bf7
FM
955 Sets the thread concurrency level for this process.
956
957 This is, roughly, the number of threads that the system tries to schedule
958 to run in parallel.
4cc4bfaf 959 The value of 0 for @a level may be used to set the default one.
78e87bf7
FM
960
961 @return @true on success or @false otherwise (for example, if this function is
962 not implemented for this platform -- currently everything except Solaris).
23324ae1
FM
963 */
964 static bool SetConcurrency(size_t level);
965
966 /**
78e87bf7
FM
967 Sets the priority of the thread, between 0 and 100.
968 It can only be set after calling Create() but before calling Run().
3c4f71cc 969
8b9aed29
RR
970 The following priorities are defined:
971 - @b WXTHREAD_MIN_PRIORITY: 0
972 - @b WXTHREAD_DEFAULT_PRIORITY: 50
973 - @b WXTHREAD_MAX_PRIORITY: 100
23324ae1 974 */
5267aefd 975 void SetPriority(unsigned int priority);
23324ae1
FM
976
977 /**
978 Pauses the thread execution for the given amount of time.
8cd8a7fe
VZ
979
980 This is the same as wxMilliSleep().
23324ae1
FM
981 */
982 static void Sleep(unsigned long milliseconds);
983
984 /**
8b9aed29 985 This function should be called periodically by the thread to ensure that
78e87bf7
FM
986 calls to Pause() and Delete() will work.
987
988 If it returns @true, the thread should exit as soon as possible.
989 Notice that under some platforms (POSIX), implementation of Pause() also
990 relies on this function being called, so not calling it would prevent
991 both stopping and suspending thread from working.
23324ae1
FM
992 */
993 virtual bool TestDestroy();
994
995 /**
78e87bf7
FM
996 Return the thread object for the calling thread.
997
998 @NULL is returned if the calling thread is the main (GUI) thread, but
999 IsMain() should be used to test whether the thread is really the main one
1000 because @NULL may also be returned for the thread not created with wxThread
1001 class. Generally speaking, the return value for such a thread is undefined.
23324ae1 1002 */
4cc4bfaf 1003 static wxThread* This();
23324ae1 1004
23324ae1
FM
1005 /**
1006 Waits for a joinable thread to terminate and returns the value the thread
5cba3a25
FM
1007 returned from Entry() or @c "(ExitCode)-1" on error. Notice that, unlike
1008 Delete(), this function doesn't cancel the thread in any way so the caller
1009 waits for as long as it takes to the thread to exit.
78e87bf7 1010
5cba3a25 1011 You can only Wait() for @b joinable (not detached) threads.
23324ae1 1012 This function can only be called from another thread context.
78e87bf7
FM
1013
1014 See @ref thread_deletion for a broader explanation of this routine.
23324ae1 1015 */
5267aefd 1016 ExitCode Wait();
23324ae1
FM
1017
1018 /**
8b9aed29
RR
1019 Give the rest of the thread time slice to the system allowing the other
1020 threads to run.
78e87bf7 1021
23324ae1 1022 Note that using this function is @b strongly discouraged, since in
78e87bf7
FM
1023 many cases it indicates a design weakness of your threading model
1024 (as does using Sleep() functions).
1025
23324ae1
FM
1026 Threads should use the CPU in an efficient manner, i.e. they should
1027 do their current work efficiently, then as soon as the work is done block
78e87bf7
FM
1028 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...) which will
1029 get signalled e.g. by other threads or a user device once further thread
1030 work is available.
1031 Using Yield() or Sleep() indicates polling-type behaviour, since we're
1032 fuzzily giving up our timeslice and wait until sometime later we'll get
1033 reactivated, at which time we realize that there isn't really much to do
1034 and Yield() again...
1035
1036 The most critical characteristic of Yield() is that it's operating system
23324ae1
FM
1037 specific: there may be scheduler changes which cause your thread to not
1038 wake up relatively soon again, but instead many seconds later,
78e87bf7
FM
1039 causing huge performance issues for your application.
1040
1041 <strong>
1042 With a well-behaving, CPU-efficient thread the operating system is likely
1043 to properly care for its reactivation the moment it needs it, whereas with
23324ae1 1044 non-deterministic, Yield-using threads all bets are off and the system
78e87bf7 1045 scheduler is free to penalize drastically</strong>, and this effect gets worse
23324ae1 1046 with increasing system load due to less free CPU resources available.
78e87bf7 1047 You may refer to various Linux kernel @c sched_yield discussions for more
23324ae1 1048 information.
78e87bf7 1049
23324ae1
FM
1050 See also Sleep().
1051 */
adaaa686 1052 static void Yield();
551266a9
FM
1053
1054protected:
1055
1056 /**
1057 This is the entry point of the thread.
1058
1059 This function is pure virtual and must be implemented by any derived class.
1060 The thread execution will start here.
1061
1062 The returned value is the thread exit code which is only useful for
1063 joinable threads and is the value returned by Wait().
1064 This function is called by wxWidgets itself and should never be called
1065 directly.
1066 */
5267aefd 1067 virtual ExitCode Entry() = 0;
551266a9
FM
1068
1069 /**
1070 This is a protected function of the wxThread class and thus can only be called
1071 from a derived class. It also can only be called in the context of this
1072 thread, i.e. a thread can only exit from itself, not from another thread.
1073
1074 This function will terminate the OS thread (i.e. stop the associated path of
1075 execution) and also delete the associated C++ object for detached threads.
1076 OnExit() will be called just before exiting.
1077 */
1078 void Exit(ExitCode exitcode = 0);
23324ae1
FM
1079};
1080
78e87bf7
FM
1081
1082/** See wxSemaphore. */
1083enum wxSemaError
1084{
1085 wxSEMA_NO_ERROR = 0,
1086 wxSEMA_INVALID, //!< semaphore hasn't been initialized successfully
1087 wxSEMA_BUSY, //!< returned by TryWait() if Wait() would block
1088 wxSEMA_TIMEOUT, //!< returned by WaitTimeout()
1089 wxSEMA_OVERFLOW, //!< Post() would increase counter past the max
1090 wxSEMA_MISC_ERROR
1091};
1092
23324ae1
FM
1093/**
1094 @class wxSemaphore
7c913512 1095
23324ae1
FM
1096 wxSemaphore is a counter limiting the number of threads concurrently accessing
1097 a shared resource. This counter is always between 0 and the maximum value
1098 specified during the semaphore creation. When the counter is strictly greater
78e87bf7
FM
1099 than 0, a call to wxSemaphore::Wait() returns immediately and decrements the
1100 counter. As soon as it reaches 0, any subsequent calls to wxSemaphore::Wait
1101 block and only return when the semaphore counter becomes strictly positive
1102 again as the result of calling wxSemaphore::Post which increments the counter.
7c913512 1103
23324ae1 1104 In general, semaphores are useful to restrict access to a shared resource
78e87bf7
FM
1105 which can only be accessed by some fixed number of clients at the same time.
1106 For example, when modeling a hotel reservation system a semaphore with the counter
23324ae1 1107 equal to the total number of available rooms could be created. Each time a room
78e87bf7
FM
1108 is reserved, the semaphore should be acquired by calling wxSemaphore::Wait
1109 and each time a room is freed it should be released by calling wxSemaphore::Post.
7c913512 1110
23324ae1 1111 @library{wxbase}
27608f11 1112 @category{threading}
23324ae1 1113*/
7c913512 1114class wxSemaphore
23324ae1
FM
1115{
1116public:
1117 /**
4cc4bfaf 1118 Specifying a @a maxcount of 0 actually makes wxSemaphore behave as if
78e87bf7 1119 there is no upper limit. If @a maxcount is 1, the semaphore behaves almost as a
23324ae1
FM
1120 mutex (but unlike a mutex it can be released by a thread different from the one
1121 which acquired it).
78e87bf7 1122
4cc4bfaf
FM
1123 @a initialcount is the initial value of the semaphore which must be between
1124 0 and @a maxcount (if it is not set to 0).
23324ae1
FM
1125 */
1126 wxSemaphore(int initialcount = 0, int maxcount = 0);
1127
1128 /**
1129 Destructor is not virtual, don't use this class polymorphically.
1130 */
1131 ~wxSemaphore();
1132
1133 /**
1134 Increments the semaphore count and signals one of the waiting
78e87bf7 1135 threads in an atomic way. Returns @e wxSEMA_OVERFLOW if the count
23324ae1 1136 would increase the counter past the maximum.
3c4f71cc 1137
d29a9a8a 1138 @return One of:
78e87bf7
FM
1139 - wxSEMA_NO_ERROR: There was no error.
1140 - wxSEMA_INVALID : Semaphore hasn't been initialized successfully.
1141 - wxSEMA_OVERFLOW: Post() would increase counter past the max.
1142 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1143 */
1144 wxSemaError Post();
1145
1146 /**
1147 Same as Wait(), but returns immediately.
3c4f71cc 1148
d29a9a8a 1149 @return One of:
78e87bf7
FM
1150 - wxSEMA_NO_ERROR: There was no error.
1151 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1152 - wxSEMA_BUSY: Returned by TryWait() if Wait() would block, i.e. the count is zero.
1153 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1154 */
1155 wxSemaError TryWait();
1156
1157 /**
1158 Wait indefinitely until the semaphore count becomes strictly positive
1159 and then decrement it and return.
3c4f71cc 1160
d29a9a8a 1161 @return One of:
78e87bf7
FM
1162 - wxSEMA_NO_ERROR: There was no error.
1163 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1164 - wxSEMA_MISC_ERROR: Miscellaneous error.
23324ae1
FM
1165 */
1166 wxSemaError Wait();
78e87bf7
FM
1167
1168 /**
1169 Same as Wait(), but with a timeout limit.
1170
1171 @return One of:
1172 - wxSEMA_NO_ERROR: There was no error.
1173 - wxSEMA_INVALID: Semaphore hasn't been initialized successfully.
1174 - wxSEMA_TIMEOUT: Timeout occurred without receiving semaphore.
1175 - wxSEMA_MISC_ERROR: Miscellaneous error.
1176 */
5267aefd 1177 wxSemaError WaitTimeout(unsigned long timeout_millis);
23324ae1
FM
1178};
1179
1180
e54c96f1 1181
23324ae1
FM
1182/**
1183 @class wxMutexLocker
7c913512 1184
78e87bf7
FM
1185 This is a small helper class to be used with wxMutex objects.
1186
1187 A wxMutexLocker acquires a mutex lock in the constructor and releases
23324ae1
FM
1188 (or unlocks) the mutex in the destructor making it much more difficult to
1189 forget to release a mutex (which, in general, will promptly lead to serious
78e87bf7 1190 problems). See wxMutex for an example of wxMutexLocker usage.
7c913512 1191
23324ae1 1192 @library{wxbase}
27608f11 1193 @category{threading}
7c913512 1194
e54c96f1 1195 @see wxMutex, wxCriticalSectionLocker
23324ae1 1196*/
7c913512 1197class wxMutexLocker
23324ae1
FM
1198{
1199public:
1200 /**
1201 Constructs a wxMutexLocker object associated with mutex and locks it.
0dd88987 1202 Call IsOk() to check if the mutex was successfully locked.
23324ae1
FM
1203 */
1204 wxMutexLocker(wxMutex& mutex);
1205
1206 /**
1207 Destructor releases the mutex if it was successfully acquired in the ctor.
1208 */
1209 ~wxMutexLocker();
1210
1211 /**
1212 Returns @true if mutex was acquired in the constructor, @false otherwise.
1213 */
328f5751 1214 bool IsOk() const;
23324ae1
FM
1215};
1216
1217
3ad41c28
RR
1218/**
1219 The possible wxMutex kinds.
1220*/
1221enum wxMutexType
1222{
424c9ce7 1223 /** Normal non-recursive mutex: try to always use this one. */
78e87bf7 1224 wxMUTEX_DEFAULT,
3ad41c28 1225
9c5313d1 1226 /** Recursive mutex: don't use these ones with wxCondition. */
78e87bf7 1227 wxMUTEX_RECURSIVE
3ad41c28
RR
1228};
1229
1230
1231/**
1232 The possible wxMutex errors.
1233*/
1234enum wxMutexError
1235{
9c5313d1 1236 /** The operation completed successfully. */
78e87bf7
FM
1237 wxMUTEX_NO_ERROR = 0,
1238
9c5313d1 1239 /** The mutex hasn't been initialized. */
78e87bf7
FM
1240 wxMUTEX_INVALID,
1241
1242 /** The mutex is already locked by the calling thread. */
1243 wxMUTEX_DEAD_LOCK,
1244
9c5313d1 1245 /** The mutex is already locked by another thread. */
78e87bf7
FM
1246 wxMUTEX_BUSY,
1247
9c5313d1 1248 /** An attempt to unlock a mutex which is not locked. */
78e87bf7
FM
1249 wxMUTEX_UNLOCKED,
1250
9c5313d1 1251 /** wxMutex::LockTimeout() has timed out. */
78e87bf7
FM
1252 wxMUTEX_TIMEOUT,
1253
9c5313d1 1254 /** Any other error */
78e87bf7 1255 wxMUTEX_MISC_ERROR
3ad41c28
RR
1256};
1257
1258
23324ae1
FM
1259/**
1260 @class wxMutex
7c913512 1261
23324ae1
FM
1262 A mutex object is a synchronization object whose state is set to signaled when
1263 it is not owned by any thread, and nonsignaled when it is owned. Its name comes
1264 from its usefulness in coordinating mutually-exclusive access to a shared
1265 resource as only one thread at a time can own a mutex object.
7c913512 1266
23324ae1
FM
1267 Mutexes may be recursive in the sense that a thread can lock a mutex which it
1268 had already locked before (instead of dead locking the entire process in this
1269 situation by starting to wait on a mutex which will never be released while the
7c913512 1270 thread is waiting) but using them is not recommended under Unix and they are
424c9ce7 1271 @b not recursive by default. The reason for this is that recursive
23324ae1 1272 mutexes are not supported by all Unix flavours and, worse, they cannot be used
424c9ce7 1273 with wxCondition.
7c913512 1274
23324ae1
FM
1275 For example, when several threads use the data stored in the linked list,
1276 modifications to the list should only be allowed to one thread at a time
1277 because during a new node addition the list integrity is temporarily broken
5cba3a25 1278 (this is also called @e program @e invariant).
7c913512 1279
3ad41c28
RR
1280 @code
1281 // this variable has an "s_" prefix because it is static: seeing an "s_" in
1282 // a multithreaded program is in general a good sign that you should use a
1283 // mutex (or a critical section)
1284 static wxMutex *s_mutexProtectingTheGlobalData;
1285
1286 // we store some numbers in this global array which is presumably used by
1287 // several threads simultaneously
1288 wxArrayInt s_data;
1289
1290 void MyThread::AddNewNode(int num)
1291 {
1292 // ensure that no other thread accesses the list
1293 s_mutexProtectingTheGlobalList->Lock();
1294
1295 s_data.Add(num);
1296
1297 s_mutexProtectingTheGlobalList->Unlock();
1298 }
1299
1300 // return true if the given number is greater than all array elements
1301 bool MyThread::IsGreater(int num)
1302 {
1303 // before using the list we must acquire the mutex
1304 wxMutexLocker lock(s_mutexProtectingTheGlobalData);
1305
1306 size_t count = s_data.Count();
1307 for ( size_t n = 0; n < count; n++ )
1308 {
1309 if ( s_data[n] > num )
1310 return false;
1311 }
1312
1313 return true;
1314 }
1315 @endcode
1316
1317 Notice how wxMutexLocker was used in the second function to ensure that the
1318 mutex is unlocked in any case: whether the function returns true or false
5cba3a25
FM
1319 (because the destructor of the local object @e lock is always called).
1320 Using this class instead of directly using wxMutex is, in general, safer
1321 and is even more so if your program uses C++ exceptions.
3ad41c28 1322
23324ae1 1323 @library{wxbase}
27608f11 1324 @category{threading}
7c913512 1325
e54c96f1 1326 @see wxThread, wxCondition, wxMutexLocker, wxCriticalSection
23324ae1 1327*/
7c913512 1328class wxMutex
23324ae1
FM
1329{
1330public:
1331 /**
1332 Default constructor.
1333 */
1334 wxMutex(wxMutexType type = wxMUTEX_DEFAULT);
1335
1336 /**
1337 Destroys the wxMutex object.
1338 */
1339 ~wxMutex();
1340
1341 /**
78e87bf7
FM
1342 Locks the mutex object.
1343 This is equivalent to LockTimeout() with infinite timeout.
3c4f71cc 1344
0dd88987 1345 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK.
23324ae1
FM
1346 */
1347 wxMutexError Lock();
1348
1349 /**
1350 Try to lock the mutex object during the specified time interval.
3c4f71cc 1351
0dd88987 1352 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_DEAD_LOCK, @c wxMUTEX_TIMEOUT.
23324ae1
FM
1353 */
1354 wxMutexError LockTimeout(unsigned long msec);
1355
1356 /**
1357 Tries to lock the mutex object. If it can't, returns immediately with an error.
3c4f71cc 1358
0dd88987 1359 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_BUSY.
23324ae1
FM
1360 */
1361 wxMutexError TryLock();
1362
1363 /**
1364 Unlocks the mutex object.
3c4f71cc 1365
0dd88987 1366 @return One of: @c wxMUTEX_NO_ERROR, @c wxMUTEX_UNLOCKED.
23324ae1
FM
1367 */
1368 wxMutexError Unlock();
1369};
1370
1371
e54c96f1 1372
23324ae1
FM
1373// ============================================================================
1374// Global functions/macros
1375// ============================================================================
1376
3950d49c
BP
1377/** @ingroup group_funcmacro_thread */
1378//@{
1379
23324ae1 1380/**
3950d49c
BP
1381 This macro declares a (static) critical section object named @a cs if
1382 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1383
1384 @header{wx/thread.h}
23324ae1 1385*/
3950d49c
BP
1386#define wxCRIT_SECT_DECLARE(cs)
1387
1388/**
1389 This macro declares a critical section object named @a cs if
1390 @c wxUSE_THREADS is 1 and does nothing if it is 0. As it doesn't include
1391 the @c static keyword (unlike wxCRIT_SECT_DECLARE()), it can be used to
1392 declare a class or struct member which explains its name.
1393
1394 @header{wx/thread.h}
1395*/
1396#define wxCRIT_SECT_DECLARE_MEMBER(cs)
23324ae1
FM
1397
1398/**
3950d49c
BP
1399 This macro creates a wxCriticalSectionLocker named @a name and associated
1400 with the critical section @a cs if @c wxUSE_THREADS is 1 and does nothing
1401 if it is 0.
1402
1403 @header{wx/thread.h}
1404*/
1405#define wxCRIT_SECT_LOCKER(name, cs)
1406
1407/**
1408 This macro combines wxCRIT_SECT_DECLARE() and wxCRIT_SECT_LOCKER(): it
1409 creates a static critical section object and also the lock object
1410 associated with it. Because of this, it can be only used inside a function,
1411 not at global scope. For example:
4cc4bfaf 1412
23324ae1
FM
1413 @code
1414 int IncCount()
1415 {
1416 static int s_counter = 0;
7c913512 1417
23324ae1 1418 wxCRITICAL_SECTION(counter);
7c913512 1419
23324ae1
FM
1420 return ++s_counter;
1421 }
1422 @endcode
7c913512 1423
3950d49c
BP
1424 Note that this example assumes that the function is called the first time
1425 from the main thread so that the critical section object is initialized
1426 correctly by the time other threads start calling it, if this is not the
1427 case this approach can @b not be used and the critical section must be made
1428 a global instead.
1429
1430 @header{wx/thread.h}
23324ae1 1431*/
3950d49c 1432#define wxCRITICAL_SECTION(name)
23324ae1
FM
1433
1434/**
3950d49c
BP
1435 This macro is equivalent to
1436 @ref wxCriticalSection::Leave "critical_section.Leave()" if
1437 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1438
1439 @header{wx/thread.h}
1440*/
1441#define wxLEAVE_CRIT_SECT(critical_section)
1442
1443/**
1444 This macro is equivalent to
1445 @ref wxCriticalSection::Enter "critical_section.Enter()" if
1446 @c wxUSE_THREADS is 1 and does nothing if it is 0.
1447
1448 @header{wx/thread.h}
1449*/
1450#define wxENTER_CRIT_SECT(critical_section)
1451
1452/**
1453 Returns @true if this thread is the main one. Always returns @true if
1454 @c wxUSE_THREADS is 0.
1455
1456 @header{wx/thread.h}
23324ae1 1457*/
3950d49c 1458bool wxIsMainThread();
23324ae1
FM
1459
1460/**
1461 This function must be called when any thread other than the main GUI thread
3950d49c
BP
1462 wants to get access to the GUI library. This function will block the
1463 execution of the calling thread until the main thread (or any other thread
1464 holding the main GUI lock) leaves the GUI library and no other thread will
1465 enter the GUI library until the calling thread calls wxMutexGuiLeave().
1466
23324ae1 1467 Typically, these functions are used like this:
4cc4bfaf 1468
23324ae1
FM
1469 @code
1470 void MyThread::Foo(void)
1471 {
3950d49c
BP
1472 // before doing any GUI calls we must ensure that
1473 // this thread is the only one doing it!
7c913512 1474
23324ae1 1475 wxMutexGuiEnter();
7c913512 1476
23324ae1
FM
1477 // Call GUI here:
1478 my_window-DrawSomething();
7c913512 1479
23324ae1
FM
1480 wxMutexGuiLeave();
1481 }
1482 @endcode
7c913512 1483
23324ae1
FM
1484 This function is only defined on platforms which support preemptive
1485 threads.
3950d49c
BP
1486
1487 @note Under GTK, no creation of top-level windows is allowed in any thread
1488 but the main one.
1489
1490 @header{wx/thread.h}
23324ae1
FM
1491*/
1492void wxMutexGuiEnter();
1493
1494/**
3950d49c
BP
1495 This function is only defined on platforms which support preemptive
1496 threads.
23324ae1 1497
3950d49c 1498 @see wxMutexGuiEnter()
23324ae1 1499
3950d49c 1500 @header{wx/thread.h}
23324ae1 1501*/
3950d49c 1502void wxMutexGuiLeave();
23324ae1 1503
3950d49c 1504//@}
23324ae1 1505