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