]> git.saurik.com Git - wxWidgets.git/blob - docs/latex/wx/thread.tex
add discussion about the problems of using Yield() part of patch 1806283)
[wxWidgets.git] / docs / latex / wx / thread.tex
1 \section{\class{wxThread}}\label{wxthread}
2
3 A thread is basically a path of execution through a program. Threads are
4 sometimes called {\it light-weight processes}, but the fundamental difference
5 between threads and processes is that memory spaces of different processes are
6 separated while all threads share the same address space.
7
8 While it makes it much easier to share common data between several threads, it also
9 makes it much easier to shoot oneself in the foot, so careful use of synchronization
10 objects such as \helpref{mutexes}{wxmutex} or \helpref{critical sections}{wxcriticalsection} is recommended. In addition, don't create global thread
11 objects because they allocate memory in their constructor, which will cause
12 problems for the memory checking system.
13
14 \wxheading{Derived from}
15
16 None.
17
18 \wxheading{Include files}
19
20 <wx/thread.h>
21
22 \wxheading{Library}
23
24 \helpref{wxBase}{librarieslist}
25
26 \wxheading{See also}
27
28 \helpref{wxMutex}{wxmutex}, \helpref{wxCondition}{wxcondition}, \helpref{wxCriticalSection}{wxcriticalsection}
29
30 \latexignore{\rtfignore{\wxheading{Members}}}
31
32 \membersection{Types of wxThreads}\label{typeswxthread}
33
34 There are two types of threads in wxWidgets: {\it detached} and {\it joinable},
35 modeled after the the POSIX thread API. This is different from the Win32 API
36 where all threads are joinable.
37
38 By default wxThreads in wxWidgets use the detached behavior. Detached threads
39 delete themselves once they have completed, either by themselves when they complete
40 processing or through a call to \helpref{wxThread::Delete}{wxthreaddelete}, and thus
41 must be created on the heap (through the new operator, for example). Conversely,
42 joinable threads do not delete themselves when they are done processing and as such
43 are safe to create on the stack. Joinable threads also provide the ability
44 for one to get value it returned from \helpref{wxThread::Entry}{wxthreadentry}
45 through \helpref{wxThread::Wait}{wxthreadwait}.
46
47 You shouldn't hurry to create all the threads joinable, however, because this
48 has a disadvantage as well: you {\bf must} Wait() for a joinable thread or the
49 system resources used by it will never be freed, and you also must delete the
50 corresponding wxThread object yourself if you did not create it on the stack. In
51 contrast, detached threads are of the "fire-and-forget" kind: you only have to start
52 a detached thread and it will terminate and destroy itself.
53
54 \membersection{wxThread deletion}\label{deletionwxthread}
55
56 Regardless of whether it has terminated or not, you should call
57 \helpref{wxThread::Wait}{wxthreadwait} on a joinable thread to release its
58 memory, as outlined in \helpref{Types of wxThreads}{typeswxthread}. If you created
59 a joinable thread on the heap, remember to delete it manually with the delete
60 operator or similar means as only detached threads handle this type of memory
61 management.
62
63 Since detached threads delete themselves when they are finished processing,
64 you should take care when calling a routine on one. If you are certain the
65 thread is still running and would like to end it, you may call
66 \helpref{wxThread::Delete}{wxthreaddelete} to gracefully end it (which implies
67 that the thread will be deleted after that call to Delete()). It should be
68 implied that you should never attempt to delete a detached thread with the
69 delete operator or similar means.
70
71 As mentioned, \helpref{wxThread::Wait}{wxthreadwait} or
72 \helpref{wxThread::Delete}{wxthreaddelete} attempts to gracefully terminate
73 a joinable and detached thread, respectively. It does this by waiting until
74 the thread in question calls \helpref{wxThread::TestDestroy}{wxthreadtestdestroy}
75 or ends processing (returns from \helpref{wxThread::Entry}{wxthreadentry}).
76
77 Obviously, if the thread does call TestDestroy() and does not end the calling
78 thread will come to halt. This is why it is important to call TestDestroy() in
79 the Entry() routine of your threads as often as possible.
80
81 As a last resort you can end the thread immediately through
82 \helpref{wxThread::Kill}{wxthreadkill}. It is strongly recommended that you
83 do not do this, however, as it does not free the resources associated with
84 the object (although the wxThread object of detached threads will still be
85 deleted) and could leave the C runtime library in an undefined state.
86
87 \membersection{wxWidgets calls in secondary threads}\label{secondarywxthread}
88
89 All threads other then the "main application thread" (the one
90 \helpref{wxApp::OnInit}{wxapponinit} or your main function runs in, for
91 example) are considered "secondary threads". These include all threads created
92 by \helpref{wxThread::Create}{wxthreadcreate} or the corresponding constructors.
93
94 GUI calls, such as those to a \helpref{wxWindow}{wxwindow} or
95 \helpref{wxBitmap}{wxbitmap} are explicitly not safe at all in secondary threads
96 and could end your application prematurely. This is due to several reasons,
97 including the underlying native API and the fact that wxThread does not run a
98 GUI event loop similar to other APIs as MFC.
99
100 A workaround that works on some wxWidgets ports is calling \helpref{wxMutexGUIEnter}{wxmutexguienter}
101 before any GUI calls and then calling \helpref{wxMutexGUILeave}{wxmutexguileave} afterwords. However,
102 the recommended way is to simply process the GUI calls in the main thread
103 through an event that is posted by either \helpref{wxPostEvent}{wxpostevent} or
104 \helpref{wxEvtHandler::AddPendingEvent}{wxevthandleraddpendingevent}. This does
105 not imply that calls to these classes are thread-safe, however, as most
106 wxWidgets classes are not thread-safe, including wxString.
107
108 \membersection{Don't poll a wxThread}\label{dontpollwxthread}
109
110 A common problem users experience with wxThread is that in their main thread
111 they will check the thread every now and then to see if it has ended through
112 \helpref{wxThread::IsRunning}{wxthreadisrunning}, only to find that their
113 application has run into problems because the thread is using the default
114 behavior and has already deleted itself. Naturally, they instead attempt to
115 use joinable threads in place of the previous behavior.
116
117 However, polling a wxThread for when it has ended is in general a bad idea -
118 in fact calling a routine on any running wxThread should be avoided if
119 possible. Instead, find a way to notify yourself when the thread has ended.
120 Usually you only need to notify the main thread, in which case you can post
121 an event to it via \helpref{wxPostEvent}{wxpostevent} or
122 \helpref{wxEvtHandler::AddPendingEvent}{wxevthandleraddpendingevent}. In
123 the case of secondary threads you can call a routine of another class
124 when the thread is about to complete processing and/or set the value
125 of a variable, possibly using \helpref{mutexes}{wxmutex} and/or other
126 synchronization means if necessary.
127
128 \membersection{wxThread::wxThread}\label{wxthreadctor}
129
130 \func{}{wxThread}{\param{wxThreadKind }{kind = wxTHREAD\_DETACHED}}
131
132 This constructor creates a new detached (default) or joinable C++ thread object. It
133 does not create or start execution of the real thread -- for this you should
134 use the \helpref{Create}{wxthreadcreate} and \helpref{Run}{wxthreadrun} methods.
135
136 The possible values for {\it kind} parameters are:
137
138 \twocolwidtha{7cm}
139 \begin{twocollist}\itemsep=0pt
140 \twocolitem{{\bf wxTHREAD\_DETACHED}}{Creates a detached thread.}
141 \twocolitem{{\bf wxTHREAD\_JOINABLE}}{Creates a joinable thread.}
142 \end{twocollist}
143
144
145 \membersection{wxThread::\destruct{wxThread}}\label{wxthreaddtor}
146
147 \func{}{\destruct{wxThread}}{\void}
148
149 The destructor frees the resources associated with the thread. Notice that you
150 should never delete a detached thread -- you may only call
151 \helpref{Delete}{wxthreaddelete} on it or wait until it terminates (and auto
152 destructs) itself. Because the detached threads delete themselves, they can
153 only be allocated on the heap.
154
155 Joinable threads should be deleted explicitly. The \helpref{Delete}{wxthreaddelete} and \helpref{Kill}{wxthreadkill} functions
156 will not delete the C++ thread object. It is also safe to allocate them on
157 stack.
158
159
160 \membersection{wxThread::Create}\label{wxthreadcreate}
161
162 \func{wxThreadError}{Create}{\param{unsigned int }{stackSize = 0}}
163
164 Creates a new thread. The thread object is created in the suspended state, and you
165 should call \helpref{Run}{wxthreadrun} to start running it. You may optionally
166 specify the stack size to be allocated to it (Ignored on platforms that don't
167 support setting it explicitly, eg. Unix system without
168 \texttt{pthread\_attr\_setstacksize}). If you do not specify the stack size,
169 the system's default value is used.
170
171 {\bf Warning:} It is a good idea to explicitly specify a value as systems'
172 default values vary from just a couple of KB on some systems (BSD and
173 OS/2 systems) to one or several MB (Windows, Solaris, Linux). So, if you
174 have a thread that requires more than just a few KB of memory, you will
175 have mysterious problems on some platforms but not on the common ones. On the
176 other hand, just indicating a large stack size by default will give you
177 performance issues on those systems with small default stack since those
178 typically use fully committed memory for the stack. On the contrary, if
179 use a lot of threads (say several hundred), virtual adress space can get tight
180 unless you explicitly specify a smaller amount of thread stack space for each
181 thread.
182
183
184 \wxheading{Return value}
185
186 One of:
187
188 \twocolwidtha{7cm}
189 \begin{twocollist}\itemsep=0pt
190 \twocolitem{{\bf wxTHREAD\_NO\_ERROR}}{There was no error.}
191 \twocolitem{{\bf wxTHREAD\_NO\_RESOURCE}}{There were insufficient resources to create a new thread.}
192 \twocolitem{{\bf wxTHREAD\_RUNNING}}{The thread is already running.}
193 \end{twocollist}
194
195
196 \membersection{wxThread::Delete}\label{wxthreaddelete}
197
198 \func{wxThreadError}{Delete}{\void}
199
200 Calling \helpref{Delete}{wxthreaddelete} gracefully terminates a
201 detached thread, either when the thread calls \helpref{TestDestroy}{wxthreadtestdestroy} or finished processing.
202
203 (Note that while this could work on a joinable thread you simply should not
204 call this routine on one as afterwards you may not be able to call
205 \helpref{wxThread::Wait}{wxthreadwait} to free the memory of that thread).
206
207 See \helpref{wxThread deletion}{deletionwxthread} for a broader explanation of this routine.
208
209 %%FIXME: What does this return and why?
210
211 \membersection{wxThread::Entry}\label{wxthreadentry}
212
213 \func{virtual ExitCode}{Entry}{\void}
214
215 This is the entry point of the thread. This function is pure virtual and must
216 be implemented by any derived class. The thread execution will start here.
217
218 The returned value is the thread exit code which is only useful for
219 joinable threads and is the value returned by \helpref{Wait}{wxthreadwait}.
220
221 This function is called by wxWidgets itself and should never be called
222 directly.
223
224
225 \membersection{wxThread::Exit}\label{wxthreadexit}
226
227 \func{void}{Exit}{\param{ExitCode }{exitcode = 0}}
228
229 This is a protected function of the wxThread class and thus can only be called
230 from a derived class. It also can only be called in the context of this
231 thread, i.e. a thread can only exit from itself, not from another thread.
232
233 This function will terminate the OS thread (i.e. stop the associated path of
234 execution) and also delete the associated C++ object for detached threads.
235 \helpref{wxThread::OnExit}{wxthreadonexit} will be called just before exiting.
236
237
238 \membersection{wxThread::GetCPUCount}\label{wxthreadgetcpucount}
239
240 \func{static int}{GetCPUCount}{\void}
241
242 Returns the number of system CPUs or -1 if the value is unknown.
243
244 \wxheading{See also}
245
246 \helpref{SetConcurrency}{wxthreadsetconcurrency}
247
248
249 \membersection{wxThread::GetCurrentId}\label{wxthreadgetcurrentid}
250
251 \func{static unsigned long}{GetCurrentId}{\void}
252
253 Returns the platform specific thread ID of the current thread as a
254 long. This can be used to uniquely identify threads, even if they are
255 not wxThreads.
256
257
258 \membersection{wxThread::GetId}\label{wxthreadgetid}
259
260 \constfunc{unsigned long}{GetId}{\void}
261
262 Gets the thread identifier: this is a platform dependent number that uniquely identifies the
263 thread throughout the system during its existence (i.e. the thread identifiers may be reused).
264
265
266 \membersection{wxThread::GetPriority}\label{wxthreadgetpriority}
267
268 \constfunc{int}{GetPriority}{\void}
269
270 Gets the priority of the thread, between zero and 100.
271
272 The following priorities are defined:
273
274 \twocolwidtha{7cm}
275 \begin{twocollist}\itemsep=0pt
276 \twocolitem{{\bf WXTHREAD\_MIN\_PRIORITY}}{0}
277 \twocolitem{{\bf WXTHREAD\_DEFAULT\_PRIORITY}}{50}
278 \twocolitem{{\bf WXTHREAD\_MAX\_PRIORITY}}{100}
279 \end{twocollist}
280
281
282 \membersection{wxThread::IsAlive}\label{wxthreadisalive}
283
284 \constfunc{bool}{IsAlive}{\void}
285
286 Returns \true if the thread is alive (i.e. started and not terminating).
287
288 Note that this function can only safely be used with joinable threads, not
289 detached ones as the latter delete themselves and so when the real thread is
290 no longer alive, it is not possible to call this function because
291 the wxThread object no longer exists.
292
293 \membersection{wxThread::IsDetached}\label{wxthreadisdetached}
294
295 \constfunc{bool}{IsDetached}{\void}
296
297 Returns \true if the thread is of the detached kind, \false if it is a joinable
298 one.
299
300
301 \membersection{wxThread::IsMain}\label{wxthreadismain}
302
303 \func{static bool}{IsMain}{\void}
304
305 Returns \true if the calling thread is the main application thread.
306
307
308 \membersection{wxThread::IsPaused}\label{wxthreadispaused}
309
310 \constfunc{bool}{IsPaused}{\void}
311
312 Returns \true if the thread is paused.
313
314
315 \membersection{wxThread::IsRunning}\label{wxthreadisrunning}
316
317 \constfunc{bool}{IsRunning}{\void}
318
319 Returns \true if the thread is running.
320
321 This method may only be safely used for joinable threads, see the remark in
322 \helpref{IsAlive}{wxthreadisalive}.
323
324
325 \membersection{wxThread::Kill}\label{wxthreadkill}
326
327 \func{wxThreadError}{Kill}{\void}
328
329 Immediately terminates the target thread. {\bf This function is dangerous and should
330 be used with extreme care (and not used at all whenever possible)!} The resources
331 allocated to the thread will not be freed and the state of the C runtime library
332 may become inconsistent. Use \helpref{Delete()}{wxthreaddelete} for detached
333 threads or \helpref{Wait()}{wxthreadwait} for joinable threads instead.
334
335 For detached threads Kill() will also delete the associated C++ object.
336 However this will not happen for joinable threads and this means that you will
337 still have to delete the wxThread object yourself to avoid memory leaks.
338 In neither case \helpref{OnExit}{wxthreadonexit} of the dying thread will be
339 called, so no thread-specific cleanup will be performed.
340
341 This function can only be called from another thread context, i.e. a thread
342 cannot kill itself.
343
344 It is also an error to call this function for a thread which is not running or
345 paused (in the latter case, the thread will be resumed first) -- if you do it,
346 a {\tt wxTHREAD\_NOT\_RUNNING} error will be returned.
347
348
349 \membersection{wxThread::OnExit}\label{wxthreadonexit}
350
351 \func{void}{OnExit}{\void}
352
353 Called when the thread exits. This function is called in the context of the
354 thread associated with the wxThread object, not in the context of the main
355 thread. This function will not be called if the thread was
356 \helpref{killed}{wxthreadkill}.
357
358 This function should never be called directly.
359
360
361 \membersection{wxThread::Pause}\label{wxthreadpause}
362
363 \func{wxThreadError}{Pause}{\void}
364
365 Suspends the thread. Under some implementations (Win32), the thread is
366 suspended immediately, under others it will only be suspended when it calls
367 \helpref{TestDestroy}{wxthreadtestdestroy} for the next time (hence, if the
368 thread doesn't call it at all, it won't be suspended).
369
370 This function can only be called from another thread context.
371
372
373 \membersection{wxThread::Run}\label{wxthreadrun}
374
375 \func{wxThreadError}{Run}{\void}
376
377 Starts the thread execution. Should be called after
378 \helpref{Create}{wxthreadcreate}.
379
380 This function can only be called from another thread context.
381
382
383 \membersection{wxThread::SetPriority}\label{wxthreadsetpriority}
384
385 \func{void}{SetPriority}{\param{int}{ priority}}
386
387 Sets the priority of the thread, between $0$ and $100$. It can only be set
388 after calling \helpref{Create()}{wxthreadcreate} but before calling
389 \helpref{Run()}{wxthreadrun}.
390
391 The following priorities are already defined:
392
393 \twocolwidtha{7cm}
394 \begin{twocollist}\itemsep=0pt
395 \twocolitem{{\bf WXTHREAD\_MIN\_PRIORITY}}{0}
396 \twocolitem{{\bf WXTHREAD\_DEFAULT\_PRIORITY}}{50}
397 \twocolitem{{\bf WXTHREAD\_MAX\_PRIORITY}}{100}
398 \end{twocollist}
399
400
401 \membersection{wxThread::Sleep}\label{wxthreadsleep}
402
403 \func{static void}{Sleep}{\param{unsigned long }{milliseconds}}
404
405 Pauses the thread execution for the given amount of time.
406
407 This function should be used instead of \helpref{wxSleep}{wxsleep} by all worker
408 threads (i.e. all except the main one).
409
410
411 \membersection{wxThread::Resume}\label{wxthreadresume}
412
413 \func{wxThreadError}{Resume}{\void}
414
415 Resumes a thread suspended by the call to \helpref{Pause}{wxthreadpause}.
416
417 This function can only be called from another thread context.
418
419
420 \membersection{wxThread::SetConcurrency}\label{wxthreadsetconcurrency}
421
422 \func{static bool}{SetConcurrency}{\param{size\_t }{level}}
423
424 Sets the thread concurrency level for this process. This is, roughly, the
425 number of threads that the system tries to schedule to run in parallel.
426 The value of $0$ for {\it level} may be used to set the default one.
427
428 Returns \true on success or false otherwise (for example, if this function is
429 not implemented for this platform -- currently everything except Solaris).
430
431
432 \membersection{wxThread::TestDestroy}\label{wxthreadtestdestroy}
433
434 \func{virtual bool}{TestDestroy}{\void}
435
436 This function should be called periodically by the thread to ensure that calls
437 to \helpref{Pause}{wxthreadpause} and \helpref{Delete}{wxthreaddelete} will
438 work. If it returns \true, the thread should exit as soon as possible.
439
440 Notice that under some platforms (POSIX), implementation of
441 \helpref{Pause}{wxthreadpause} also relies on this function being called, so
442 not calling it would prevent both stopping and suspending thread from working.
443
444
445 \membersection{wxThread::This}\label{wxthreadthis}
446
447 \func{static wxThread *}{This}{\void}
448
449 Return the thread object for the calling thread. NULL is returned if the calling thread
450 is the main (GUI) thread, but \helpref{IsMain}{wxthreadismain} should be used to test
451 whether the thread is really the main one because NULL may also be returned for the thread
452 not created with wxThread class. Generally speaking, the return value for such a thread
453 is undefined.
454
455
456 \membersection{wxThread::Yield}\label{wxthreadyield}
457
458 \func{void}{Yield}{\void}
459
460 Give the rest of the thread time slice to the system allowing the other threads to run.
461 Note that using this function is {\bf strongly discouraged}, since in
462 many cases it indicates a design weakness of your threading model (as
463 does using Sleep functions).
464 Threads should use the CPU in an efficient manner, i.e. they should
465 do their current work efficiently, then as soon as the work is done block
466 on a wakeup event (wxCondition, wxMutex, select(), poll(), ...)
467 which will get signalled e.g. by other threads or a user device once further
468 thread work is available. Using Yield or Sleep
469 indicates polling-type behaviour, since we're fuzzily giving up our timeslice
470 and wait until sometime later we'll get reactivated, at which time we
471 realize that there isn't really much to do and Yield again...
472 The most critical characteristic of Yield is that it's operating system
473 specific: there may be scheduler changes which cause your thread to not
474 wake up relatively soon again, but instead many seconds later,
475 causing huge performance issues for your application. {\bf with a
476 well-behaving, CPU-efficient thread the operating system is likely to properly
477 care for its reactivation the moment it needs it, whereas with
478 non-deterministic, Yield-using threads all bets are off and the system
479 scheduler is free to penalize drastically}, and this effect gets worse
480 with increasing system load due to less free CPU resources available.
481 You may refer to various Linux kernel sched\_yield discussions for more information.
482 See also \helpref{Sleep()}{wxthreadsleep}.
483
484
485 \membersection{wxThread::Wait}\label{wxthreadwait}
486
487 \constfunc{ExitCode}{Wait}{\void}
488
489 Waits for a joinable thread to terminate and returns the value the thread
490 returned from \helpref{wxThread::Entry}{wxthreadentry} or {\tt (ExitCode)-1} on
491 error. Notice that, unlike \helpref{Delete}{wxthreaddelete} doesn't cancel the
492 thread in any way so the caller waits for as long as it takes to the thread to
493 exit.
494
495 You can only Wait() for joinable (not detached) threads.
496
497 This function can only be called from another thread context.
498
499 See \helpref{wxThread deletion}{deletionwxthread} for a broader explanation of this routine.
500