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{wxBase
}{librarieslist
}
28 \helpref{wxMutex
}{wxmutex
},
\helpref{wxCondition
}{wxcondition
},
\helpref{wxCriticalSection
}{wxcriticalsection
}
30 \latexignore{\rtfignore{\wxheading{Members
}}}
32 \membersection{Types of wxThreads
}\label{typeswxthread
}
34 There are two types of threads in wxWidgets:
{\it detached
} and
{\it joinable
},
35 modeled after the the POSIX thread API. This is different from the Win32 API
36 where all threads are joinable.
38 By default wxThreads in wxWidgets use the detached behavior. Detached threads
39 delete themselves once they have completed, either by themselves when they complete
40 processing or through a call to
\helpref{wxThread::Delete
}{wxthreaddelete
}, and thus
41 must be created on the heap (through the new operator, for example). Conversely,
42 joinable threads do not delete themselves when they are done processing and as such
43 are safe to create on the stack. Joinable threads also provide the ability
44 for one to get value it returned from
\helpref{wxThread::Entry
}{wxthreadentry
}
45 through
\helpref{wxThread::Wait
}{wxthreadwait
}.
47 You shouldn't hurry to create all the threads joinable, however, because this
48 has a disadvantage as well: you
{\bf must
} Wait() for a joinable thread or the
49 system resources used by it will never be freed, and you also must delete the
50 corresponding wxThread object yourself if you did not create it on the stack. In
51 contrast, detached threads are of the "fire-and-forget" kind: you only have to start
52 a detached thread and it will terminate and destroy itself.
54 \membersection{wxThread deletion
}\label{deletionwxthread
}
56 Regardless of whether it has terminated or not, you should call
57 \helpref{wxThread::Wait
}{wxthreadwait
} on a joinable thread to release its
58 memory, as outlined in
\helpref{Types of wxThreads
}{typeswxthread
}. If you created
59 a joinable thread on the heap, remember to delete it manually with the delete
60 operator or similar means as only detached threads handle this type of memory
63 Since detached threads delete themselves when they are finished processing,
64 you should take care when calling a routine on one. If you are certain the
65 thread is still running and would like to end it, you may call
66 \helpref{wxThread::Delete
}{wxthreaddelete
} to gracefully end it (which implies
67 that the thread will be deleted after that call to Delete()). It should be
68 implied that you should never attempt to delete a detached thread with the
69 delete operator or similar means.
71 As mentioned,
\helpref{wxThread::Wait
}{wxthreadwait
} or
72 \helpref{wxThread::Delete
}{wxthreaddelete
} attempts to gracefully terminate
73 a joinable and detached thread, respectively. It does this by waiting until
74 the thread in question calls
\helpref{wxThread::TestDestroy
}{wxthreadtestdestroy
}
75 or ends processing (returns from
\helpref{wxThread::Entry
}{wxthreadentry
}).
77 Obviously, if the thread does call TestDestroy() and does not end the calling
78 thread will come to halt. This is why it is important to call TestDestroy() in
79 the Entry() routine of your threads as often as possible.
81 As a last resort you can end the thread immediately through
82 \helpref{wxThread::Kill
}{wxthreadkill
}. It is strongly recommended that you
83 do not do this, however, as it does not free the resources associated with
84 the object (although the wxThread object of detached threads will still be
85 deleted) and could leave the C runtime library in an undefined state.
87 \membersection{wxWidgets calls in secondary threads
}\label{secondarywxthread
}
89 All threads other then the "main application thread" (the one
90 \helpref{wxApp::OnInit
}{wxapponinit
} or your main function runs in, for
91 example) are considered "secondary threads". These include all threads created
92 by
\helpref{wxThread::Create
}{wxthreadcreate
} or the corresponding constructors.
94 GUI calls, such as those to a
\helpref{wxWindow
}{wxwindow
} or
95 \helpref{wxBitmap
}{wxbitmap
} are explicitly not safe at all in secondary threads
96 and could end your application prematurely. This is due to several reasons,
97 including the underlying native API and the fact that wxThread does not run a
98 GUI event loop similar to other APIs as MFC.
100 A workaround that works on some wxWidgets ports is calling
\helpref{wxMutexGUIEnter
}{wxmutexguienter
}
101 before any GUI calls and then calling
\helpref{wxMutexGUILeave
}{wxmutexguileave
} afterwords. However,
102 the recommended way is to simply process the GUI calls in the main thread
103 through an event that is posted by either
\helpref{wxPostEvent
}{wxpostevent
} or
104 \helpref{wxEvtHandler::AddPendingEvent
}{wxevthandleraddpendingevent
}. This does
105 not imply that calls to these classes are thread-safe, however, as most
106 wxWidgets classes are not thread-safe, including wxString.
108 \membersection{Don't poll a wxThread
}\label{dontpollwxthread
}
110 A common problem users experience with wxThread is that in their main thread
111 they 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
113 application has run into problems because the thread is using the default
114 behavior and has already deleted itself. Naturally, they instead attempt to
115 use joinable threads in place of the previous behavior.
117 However, polling a wxThread for when it has ended is in general a bad idea -
118 in fact calling a routine on any running wxThread should be avoided if
119 possible. Instead, find a way to notify yourself when the thread has ended.
120 Usually you only need to notify the main thread, in which case you can post
121 an event to it via
\helpref{wxPostEvent
}{wxpostevent
} or
122 \helpref{wxEvtHandler::AddPendingEvent
}{wxevthandleraddpendingevent
}. In
123 the case of secondary threads you can call a routine of another class
124 when the thread is about to complete processing and/or set the value
125 of a variable, possibly using
\helpref{mutexes
}{wxmutex
} and/or other
126 synchronization means if necessary.
128 \membersection{wxThread::wxThread
}\label{wxthreadctor
}
130 \func{}{wxThread
}{\param{wxThreadKind
}{kind = wxTHREAD
\_DETACHED}}
132 This constructor creates a new detached (default) or joinable C++ thread object. It
133 does not create or start execution of the real thread -- for this you should
134 use the
\helpref{Create
}{wxthreadcreate
} and
\helpref{Run
}{wxthreadrun
} methods.
136 The possible values for
{\it kind
} parameters are:
139 \begin{twocollist
}\itemsep=
0pt
140 \twocolitem{{\bf wxTHREAD
\_DETACHED}}{Creates a detached thread.
}
141 \twocolitem{{\bf wxTHREAD
\_JOINABLE}}{Creates a joinable thread.
}
145 \membersection{wxThread::
\destruct{wxThread
}}\label{wxthreaddtor
}
147 \func{}{\destruct{wxThread
}}{\void}
149 The destructor frees the resources associated with the thread. Notice that you
150 should never delete a detached thread -- you may only call
151 \helpref{Delete
}{wxthreaddelete
} on it or wait until it terminates (and auto
152 destructs) itself. Because the detached threads delete themselves, they can
153 only be allocated on the heap.
155 Joinable threads should be deleted explicitly. The
\helpref{Delete
}{wxthreaddelete
} and
\helpref{Kill
}{wxthreadkill
} functions
156 will not delete the C++ thread object. It is also safe to allocate them on
160 \membersection{wxThread::Create
}\label{wxthreadcreate
}
162 \func{wxThreadError
}{Create
}{\param{unsigned int
}{stackSize =
0}}
164 Creates a new thread. The thread object is created in the suspended state, and you
165 should call
\helpref{Run
}{wxthreadrun
} to start running it. You may optionally
166 specify the stack size to be allocated to it (Ignored on platforms that don't
167 support setting it explicitly, eg. Unix system without
168 \texttt{pthread
\_attr\_setstacksize}). If you do not specify the stack size,
169 the system's default value is used.
171 {\bf Warning:
} It is a good idea to explicitly specify a value as systems'
172 default values vary from just a couple of KB on some systems (BSD and
173 OS/
2 systems) to one or several MB (Windows, Solaris, Linux). So, if you
174 have a thread that requires more than just a few KB of memory, you will
175 have mysterious problems on some platforms but not on the common ones. On the
176 other hand, just indicating a large stack size by default will give you
177 performance issues on those systems with small default stack since those
178 typically use fully committed memory for the stack. On the contrary, if
179 use a lot of threads (say several hundred), virtual adress space can get tight
180 unless you explicitly specify a smaller amount of thread stack space for each
184 \wxheading{Return value
}
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.
}
196 \membersection{wxThread::Delete
}\label{wxthreaddelete
}
198 \func{wxThreadError
}{Delete
}{\void}
200 Calling
\helpref{Delete
}{wxthreaddelete
} gracefully terminates a
201 detached thread, either when the thread calls
\helpref{TestDestroy
}{wxthreadtestdestroy
} or finished processing.
203 (Note that while this could work on a joinable thread you simply should not
204 call 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).
207 See
\helpref{wxThread deletion
}{deletionwxthread
} for a broader explanation of this routine.
209 %%FIXME: What does this return and why?
211 \membersection{wxThread::Entry
}\label{wxthreadentry
}
213 \func{virtual ExitCode
}{Entry
}{\void}
215 This is the entry point of the thread. This function is pure virtual and must
216 be implemented by any derived class. The thread execution will start here.
218 The returned value is the thread exit code which is only useful for
219 joinable threads and is the value returned by
\helpref{Wait
}{wxthreadwait
}.
221 This function is called by wxWidgets itself and should never be called
225 \membersection{wxThread::Exit
}\label{wxthreadexit
}
227 \func{void
}{Exit
}{\param{ExitCode
}{exitcode =
0}}
229 This is a protected function of the wxThread class and thus can only be called
230 from a derived class. It also can only be called in the context of this
231 thread, i.e. a thread can only exit from itself, not from another thread.
233 This function will terminate the OS thread (i.e. stop the associated path of
234 execution) and also delete the associated C++ object for detached threads.
235 \helpref{wxThread::OnExit
}{wxthreadonexit
} will be called just before exiting.
238 \membersection{wxThread::GetCPUCount
}\label{wxthreadgetcpucount
}
240 \func{static int
}{GetCPUCount
}{\void}
242 Returns the number of system CPUs or -
1 if the value is unknown.
246 \helpref{SetConcurrency
}{wxthreadsetconcurrency
}
249 \membersection{wxThread::GetCurrentId
}\label{wxthreadgetcurrentid
}
251 \func{static unsigned long
}{GetCurrentId
}{\void}
253 Returns the platform specific thread ID of the current thread as a
254 long. This can be used to uniquely identify threads, even if they are
258 \membersection{wxThread::GetId
}\label{wxthreadgetid
}
260 \constfunc{unsigned long
}{GetId
}{\void}
262 Gets the thread identifier: this is a platform dependent number that uniquely identifies the
263 thread throughout the system during its existence (i.e. the thread identifiers may be reused).
266 \membersection{wxThread::GetPriority
}\label{wxthreadgetpriority
}
268 \constfunc{int
}{GetPriority
}{\void}
270 Gets the priority of the thread, between zero and
100.
272 The following priorities are defined:
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}
282 \membersection{wxThread::IsAlive
}\label{wxthreadisalive
}
284 \constfunc{bool
}{IsAlive
}{\void}
286 Returns
\true if the thread is alive (i.e. started and not terminating).
288 Note that this function can only safely be used with joinable threads, not
289 detached ones as the latter delete themselves and so when the real thread is
290 no longer alive, it is not possible to call this function because
291 the wxThread object no longer exists.
293 \membersection{wxThread::IsDetached
}\label{wxthreadisdetached
}
295 \constfunc{bool
}{IsDetached
}{\void}
297 Returns
\true if the thread is of the detached kind,
\false if it is a joinable
301 \membersection{wxThread::IsMain
}\label{wxthreadismain
}
303 \func{static bool
}{IsMain
}{\void}
305 Returns
\true if the calling thread is the main application thread.
308 \membersection{wxThread::IsPaused
}\label{wxthreadispaused
}
310 \constfunc{bool
}{IsPaused
}{\void}
312 Returns
\true if the thread is paused.
315 \membersection{wxThread::IsRunning
}\label{wxthreadisrunning
}
317 \constfunc{bool
}{IsRunning
}{\void}
319 Returns
\true if the thread is running.
321 This method may only be safely used for joinable threads, see the remark in
322 \helpref{IsAlive
}{wxthreadisalive
}.
325 \membersection{wxThread::Kill
}\label{wxthreadkill
}
327 \func{wxThreadError
}{Kill
}{\void}
329 Immediately terminates the target thread.
{\bf This function is dangerous and should
330 be used with extreme care (and not used at all whenever possible)!
} The resources
331 allocated to the thread will not be freed and the state of the C runtime library
332 may become inconsistent. Use
\helpref{Delete()
}{wxthreaddelete
} for detached
333 threads or
\helpref{Wait()
}{wxthreadwait
} for joinable threads instead.
335 For detached threads Kill() will also delete the associated C++ object.
336 However this will not happen for joinable threads and this means that you will
337 still have to delete the wxThread object yourself to avoid memory leaks.
338 In neither case
\helpref{OnExit
}{wxthreadonexit
} of the dying thread will be
339 called, so no thread-specific cleanup will be performed.
341 This function can only be called from another thread context, i.e. a thread
344 It is also an error to call this function for a thread which is not running or
345 paused (in the latter case, the thread will be resumed first) -- if you do it,
346 a
{\tt wxTHREAD
\_NOT\_RUNNING} error will be returned.
349 \membersection{wxThread::OnExit
}\label{wxthreadonexit
}
351 \func{void
}{OnExit
}{\void}
353 Called when the thread exits. This function is called in the context of the
354 thread associated with the wxThread object, not in the context of the main
355 thread. This function will not be called if the thread was
356 \helpref{killed
}{wxthreadkill
}.
358 This function should never be called directly.
361 \membersection{wxThread::Pause
}\label{wxthreadpause
}
363 \func{wxThreadError
}{Pause
}{\void}
365 Suspends the thread. Under some implementations (Win32), the thread is
366 suspended immediately, under others it will only be suspended when it calls
367 \helpref{TestDestroy
}{wxthreadtestdestroy
} for the next time (hence, if the
368 thread doesn't call it at all, it won't be suspended).
370 This function can only be called from another thread context.
373 \membersection{wxThread::Run
}\label{wxthreadrun
}
375 \func{wxThreadError
}{Run
}{\void}
377 Starts the thread execution. Should be called after
378 \helpref{Create
}{wxthreadcreate
}.
380 This function can only be called from another thread context.
383 \membersection{wxThread::SetPriority
}\label{wxthreadsetpriority
}
385 \func{void
}{SetPriority
}{\param{int
}{ priority
}}
387 Sets the priority of the thread, between $
0$ and $
100$. It can only be set
388 after calling
\helpref{Create()
}{wxthreadcreate
} but before calling
389 \helpref{Run()
}{wxthreadrun
}.
391 The following priorities are already defined:
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}
401 \membersection{wxThread::Sleep
}\label{wxthreadsleep
}
403 \func{static void
}{Sleep
}{\param{unsigned long
}{milliseconds
}}
405 Pauses the thread execution for the given amount of time.
407 This function should be used instead of
\helpref{wxSleep
}{wxsleep
} by all worker
408 threads (i.e. all except the main one).
411 \membersection{wxThread::Resume
}\label{wxthreadresume
}
413 \func{wxThreadError
}{Resume
}{\void}
415 Resumes a thread suspended by the call to
\helpref{Pause
}{wxthreadpause
}.
417 This function can only be called from another thread context.
420 \membersection{wxThread::SetConcurrency
}\label{wxthreadsetconcurrency
}
422 \func{static bool
}{SetConcurrency
}{\param{size
\_t }{level
}}
424 Sets the thread concurrency level for this process. This is, roughly, the
425 number of threads that the system tries to schedule to run in parallel.
426 The value of $
0$ for
{\it level
} may be used to set the default one.
428 Returns
\true on success or false otherwise (for example, if this function is
429 not implemented for this platform -- currently everything except Solaris).
432 \membersection{wxThread::TestDestroy
}\label{wxthreadtestdestroy
}
434 \func{virtual bool
}{TestDestroy
}{\void}
436 This function should be called periodically by the thread to ensure that calls
437 to
\helpref{Pause
}{wxthreadpause
} and
\helpref{Delete
}{wxthreaddelete
} will
438 work. If it returns
\true, the thread should exit as soon as possible.
440 Notice that under some platforms (POSIX), implementation of
441 \helpref{Pause
}{wxthreadpause
} also relies on this function being called, so
442 not calling it would prevent both stopping and suspending thread from working.
445 \membersection{wxThread::This
}\label{wxthreadthis
}
447 \func{static wxThread *
}{This
}{\void}
449 Return the thread object for the calling thread. NULL is returned if the calling thread
450 is the main (GUI) thread, but
\helpref{IsMain
}{wxthreadismain
} should be used to test
451 whether the thread is really the main one because NULL may also be returned for the thread
452 not created with wxThread class. Generally speaking, the return value for such a thread
456 \membersection{wxThread::Yield
}\label{wxthreadyield
}
458 \func{void
}{Yield
}{\void}
460 Give the rest of the thread time slice to the system allowing the other threads to run.
461 See also
\helpref{Sleep()
}{wxthreadsleep
}.
464 \membersection{wxThread::Wait
}\label{wxthreadwait
}
466 \constfunc{ExitCode
}{Wait
}{\void}
468 Waits for a joinable thread to terminate and returns the value the thread
469 returned from
\helpref{wxThread::Entry
}{wxthreadentry
} or
{\tt (ExitCode)-
1} on
470 error. Notice that, unlike
\helpref{Delete
}{wxthreaddelete
} doesn't cancel the
471 thread in any way so the caller waits for as long as it takes to the thread to
474 You can only Wait() for joinable (not detached) threads.
476 This function can only be called from another thread context.
478 See
\helpref{wxThread deletion
}{deletionwxthread
} for a broader explanation of this routine.