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