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