]> git.saurik.com Git - wxWidgets.git/blame_incremental - docs/latex/wx/thread.tex
Added const and virtual in various places
[wxWidgets.git] / docs / latex / wx / thread.tex
... / ...
CommitLineData
1\section{\class{wxThread}}\label{wxthread}
2
3A thread is basically a path of execution through a program. Threads are
4sometimes called {\it light-weight processes}, but the fundamental difference
5between threads and processes is that memory spaces of different processes are
6separated while all threads share the same address space.
7
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.
13
14\wxheading{Derived from}
15
16None.
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
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.
127
128\membersection{wxThread::wxThread}\label{wxthreadctor}
129
130\func{}{wxThread}{\param{wxThreadKind }{kind = wxTHREAD\_DETACHED}}
131
132This constructor creates a new detached (default) or joinable C++ thread object. It
133does not create or start execution of the real thread -- for this you should
134use the \helpref{Create}{wxthreadcreate} and \helpref{Run}{wxthreadrun} methods.
135
136The 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
149The destructor frees the resources associated with the thread. Notice that you
150should never delete a detached thread -- you may only call
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
155Joinable threads should be deleted explicitly. The \helpref{Delete}{wxthreaddelete} and \helpref{Kill}{wxthreadkill} functions
156will not delete the C++ thread object. It is also safe to allocate them on
157stack.
158
159
160\membersection{wxThread::Create}\label{wxthreadcreate}
161
162\func{wxThreadError}{Create}{\param{unsigned int }{stackSize = 0}}
163
164Creates a new thread. The thread object is created in the suspended state, and you
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
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.
170
171{\bf Warning:} It is a good idea to explicitly specify a value as systems'
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
181thread.
182
183
184\wxheading{Return value}
185
186One 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
200Calling \helpref{Delete}{wxthreaddelete} gracefully terminates a
201detached 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
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).
206
207See \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
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
218The returned value is the thread exit code which is only useful for
219joinable threads and is the value returned by \helpref{Wait}{wxthreadwait}.
220
221This function is called by wxWidgets itself and should never be called
222directly.
223
224
225\membersection{wxThread::Exit}\label{wxthreadexit}
226
227\func{void}{Exit}{\param{ExitCode }{exitcode = 0}}
228
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
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
234execution) 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
242Returns 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
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
257
258\membersection{wxThread::GetId}\label{wxthreadgetid}
259
260\constfunc{unsigned long}{GetId}{\void}
261
262Gets the thread identifier: this is a platform dependent number that uniquely identifies the
263thread 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
270Gets the priority of the thread, between zero and 100.
271
272The 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
286Returns \true if the thread is alive (i.e. started and not terminating).
287
288Note that this function can only safely be used with joinable threads, not
289detached ones as the latter delete themselves and so when the real thread is
290no longer alive, it is not possible to call this function because
291the wxThread object no longer exists.
292
293\membersection{wxThread::IsDetached}\label{wxthreadisdetached}
294
295\constfunc{bool}{IsDetached}{\void}
296
297Returns \true if the thread is of the detached kind, \false if it is a joinable
298one.
299
300
301\membersection{wxThread::IsMain}\label{wxthreadismain}
302
303\func{static bool}{IsMain}{\void}
304
305Returns \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
312Returns \true if the thread is paused.
313
314
315\membersection{wxThread::IsRunning}\label{wxthreadisrunning}
316
317\constfunc{bool}{IsRunning}{\void}
318
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
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
332may become inconsistent. Use \helpref{Delete()}{wxthreaddelete} for detached
333threads or \helpref{Wait()}{wxthreadwait} for joinable threads instead.
334
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
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.
340
341This function can only be called from another thread context, i.e. a thread
342cannot kill itself.
343
344It is also an error to call this function for a thread which is not running or
345paused (in the latter case, the thread will be resumed first) -- if you do it,
346a {\tt wxTHREAD\_NOT\_RUNNING} error will be returned.
347
348
349\membersection{wxThread::OnExit}\label{wxthreadonexit}
350
351\func{void}{OnExit}{\void}
352
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
355thread. This function will not be called if the thread was
356\helpref{killed}{wxthreadkill}.
357
358This function should never be called directly.
359
360
361\membersection{wxThread::Pause}\label{wxthreadpause}
362
363\func{wxThreadError}{Pause}{\void}
364
365Suspends the thread. Under some implementations (Win32), the thread is
366suspended immediately, under others it will only be suspended when it calls
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
372
373\membersection{wxThread::Run}\label{wxthreadrun}
374
375\func{wxThreadError}{Run}{\void}
376
377Starts the thread execution. Should be called after
378\helpref{Create}{wxthreadcreate}.
379
380This 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
387Sets the priority of the thread, between $0$ and $100$. It can only be set
388after calling \helpref{Create()}{wxthreadcreate} but before calling
389\helpref{Run()}{wxthreadrun}.
390
391The 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
405Pauses the thread execution for the given amount of time.
406
407This function should be used instead of \helpref{wxSleep}{wxsleep} by all worker
408threads (i.e. all except the main one).
409
410
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
419
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
428Returns \true on success or false otherwise (for example, if this function is
429not implemented for this platform -- currently everything except Solaris).
430
431
432\membersection{wxThread::TestDestroy}\label{wxthreadtestdestroy}
433
434\func{virtual bool}{TestDestroy}{\void}
435
436This function should be called periodically by the thread to ensure that calls
437to \helpref{Pause}{wxthreadpause} and \helpref{Delete}{wxthreaddelete} will
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.
443
444
445\membersection{wxThread::This}\label{wxthreadthis}
446
447\func{static wxThread *}{This}{\void}
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
452not created with wxThread class. Generally speaking, the return value for such a thread
453is undefined.
454
455
456\membersection{wxThread::Yield}\label{wxthreadyield}
457
458\func{void}{Yield}{\void}
459
460Give the rest of the thread time slice to the system allowing the other threads to run.
461See also \helpref{Sleep()}{wxthreadsleep}.
462
463
464\membersection{wxThread::Wait}\label{wxthreadwait}
465
466\constfunc{ExitCode}{Wait}{\void}
467
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.
473
474You can only Wait() for joinable (not detached) threads.
475
476This function can only be called from another thread context.
477
478See \helpref{wxThread deletion}{deletionwxthread} for a broader explanation of this routine.
479