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