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