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