1 \section{\class{wxThread
}}\label{wxthread
}
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.
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.
14 \wxheading{Derived from
}
18 \wxheading{Include files
}
24 \helpref{wxMutex
}{wxmutex
},
\helpref{wxCondition
}{wxcondition
},
\helpref{wxCriticalSection
}{wxcriticalsection
}
26 \latexignore{\rtfignore{\wxheading{Members
}}}
28 \membersection{Types of wxThreads
}\label{typeswxthread
}
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.
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
}.
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.
50 \membersection{wxThread deletion
}\label{deletionwxthread
}
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
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.
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
}).
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.
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.
83 \membersection{wxWidgets calls in secondary threads
}\label{secondarywxthread
}
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.
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.
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.
104 \membersection{Don't poll a wxThread
}\label{dontpollwxthread
}
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.
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.
124 \membersection{wxThread::wxThread
}\label{wxthreadctor
}
126 \func{}{wxThread
}{\param{wxThreadKind
}{kind = wxTHREAD
\_DETACHED}}
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.
132 The possible values for
{\it kind
} parameters are:
135 \begin{twocollist
}\itemsep=
0pt
136 \twocolitem{{\bf wxTHREAD
\_DETACHED}}{Creates a detached thread.
}
137 \twocolitem{{\bf wxTHREAD
\_JOINABLE}}{Creates a joinable thread.
}
141 \membersection{wxThread::
\destruct{wxThread
}}\label{wxthreaddtor
}
143 \func{}{\destruct{wxThread
}}{\void}
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.
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
156 \membersection{wxThread::Create
}\label{wxthreadcreate
}
158 \func{wxThreadError
}{Create
}{\param{unsigned int
}{stackSize =
0}}
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.
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
180 \wxheading{Return value
}
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.
}
192 \membersection{wxThread::Delete
}\label{wxthreaddelete
}
194 \func{wxThreadError
}{Delete
}{\void}
196 Calling
\helpref{Delete
}{wxthreaddelete
} gracefully terminates a
197 detached thread, either when the thread calls
\helpref{TestDestroy
}{wxthreadtestdestroy
} or finished processing.
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).
203 See
\helpref{wxThread deletion
}{deletionwxthread
} for a broader explanation of this routine.
205 %%FIXME: What does this return and why?
207 \membersection{wxThread::Entry
}\label{wxthreadentry
}
209 \func{virtual ExitCode
}{Entry
}{\void}
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.
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
}.
217 This function is called by wxWidgets itself and should never be called
221 \membersection{wxThread::Exit
}\label{wxthreadexit
}
223 \func{void
}{Exit
}{\param{ExitCode
}{exitcode =
0}}
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.
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.
234 \membersection{wxThread::GetCPUCount
}\label{wxthreadgetcpucount
}
236 \func{static int
}{GetCPUCount
}{\void}
238 Returns the number of system CPUs or -
1 if the value is unknown.
242 \helpref{SetConcurrency
}{wxthreadsetconcurrency
}
245 \membersection{wxThread::GetCurrentId
}\label{wxthreadgetcurrentid
}
247 \func{static unsigned long
}{GetCurrentId
}{\void}
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
254 \membersection{wxThread::GetId
}\label{wxthreadgetid
}
256 \constfunc{unsigned long
}{GetId
}{\void}
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).
262 \membersection{wxThread::GetPriority
}\label{wxthreadgetpriority
}
264 \constfunc{int
}{GetPriority
}{\void}
266 Gets the priority of the thread, between zero and
100.
268 The following priorities are defined:
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}
278 \membersection{wxThread::IsAlive
}\label{wxthreadisalive
}
280 \constfunc{bool
}{IsAlive
}{\void}
282 Returns
\true if the thread is alive (i.e. started and not terminating).
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.
289 \membersection{wxThread::IsDetached
}\label{wxthreadisdetached
}
291 \constfunc{bool
}{IsDetached
}{\void}
293 Returns
\true if the thread is of the detached kind,
\false if it is a joinable
297 \membersection{wxThread::IsMain
}\label{wxthreadismain
}
299 \func{static bool
}{IsMain
}{\void}
301 Returns
\true if the calling thread is the main application thread.
304 \membersection{wxThread::IsPaused
}\label{wxthreadispaused
}
306 \constfunc{bool
}{IsPaused
}{\void}
308 Returns
\true if the thread is paused.
311 \membersection{wxThread::IsRunning
}\label{wxthreadisrunning
}
313 \constfunc{bool
}{IsRunning
}{\void}
315 Returns
\true if the thread is running.
317 This method may only be safely used for joinable threads, see the remark in
318 \helpref{IsAlive
}{wxthreadisalive
}.
321 \membersection{wxThread::Kill
}\label{wxthreadkill
}
323 \func{wxThreadError
}{Kill
}{\void}
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.
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.
337 This function can only be called from another thread context, i.e. a thread
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.
345 \membersection{wxThread::OnExit
}\label{wxthreadonexit
}
347 \func{void
}{OnExit
}{\void}
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
}.
354 This function should never be called directly.
357 \membersection{wxThread::Pause
}\label{wxthreadpause
}
359 \func{wxThreadError
}{Pause
}{\void}
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).
366 This function can only be called from another thread context.
369 \membersection{wxThread::Run
}\label{wxthreadrun
}
371 \func{wxThreadError
}{Run
}{\void}
373 Starts the thread execution. Should be called after
374 \helpref{Create
}{wxthreadcreate
}.
376 This function can only be called from another thread context.
379 \membersection{wxThread::SetPriority
}\label{wxthreadsetpriority
}
381 \func{void
}{SetPriority
}{\param{int
}{ priority
}}
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
}.
387 The following priorities are already defined:
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}
397 \membersection{wxThread::Sleep
}\label{wxthreadsleep
}
399 \func{static void
}{Sleep
}{\param{unsigned long
}{milliseconds
}}
401 Pauses the thread execution for the given amount of time.
403 This function should be used instead of
\helpref{wxSleep
}{wxsleep
} by all worker
404 threads (i.e. all except the main one).
407 \membersection{wxThread::Resume
}\label{wxthreadresume
}
409 \func{wxThreadError
}{Resume
}{\void}
411 Resumes a thread suspended by the call to
\helpref{Pause
}{wxthreadpause
}.
413 This function can only be called from another thread context.
416 \membersection{wxThread::SetConcurrency
}\label{wxthreadsetconcurrency
}
418 \func{static bool
}{SetConcurrency
}{\param{size
\_t }{level
}}
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.
424 Returns
\true on success or false otherwise (for example, if this function is
425 not implemented for this platform -- currently everything except Solaris).
428 \membersection{wxThread::TestDestroy
}\label{wxthreadtestdestroy
}
430 \func{virtual bool
}{TestDestroy
}{\void}
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.
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.
441 \membersection{wxThread::This
}\label{wxthreadthis
}
443 \func{static wxThread *
}{This
}{\void}
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
452 \membersection{wxThread::Yield
}\label{wxthreadyield
}
454 \func{void
}{Yield
}{\void}
456 Give the rest of the thread time slice to the system allowing the other threads to run.
457 See also
\helpref{Sleep()
}{wxthreadsleep
}.
460 \membersection{wxThread::Wait
}\label{wxthreadwait
}
462 \constfunc{ExitCode
}{Wait
}{\void}
464 Waits for a joinable thread to terminate and returns the value the thread
465 returned from
\helpref{wxThread::Entry
}{wxthreadentry
} or
{\tt (ExitCode)-
1} on
466 error. Notice that, unlike
\helpref{Delete
}{wxthreaddelete
} doesn't cancel the
467 thread in any way so the caller waits for as long as it takes to the thread to
470 You can only Wait() for joinable (not detached) threads.
472 This function can only be called from another thread context.
474 See
\helpref{wxThread deletion
}{deletionwxthread
} for a broader explanation of this routine.