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