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{See also} 23 24\helpref{wxMutex}{wxmutex}, \helpref{wxCondition}{wxcondition}, \helpref{wxCriticalSection}{wxcriticalsection} 25 26\latexignore{\rtfignore{\wxheading{Members}}} 27 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. 123 124\membersection{wxThread::wxThread}\label{wxthreadctor} 125 126\func{}{wxThread}{\param{wxThreadKind }{kind = wxTHREAD\_DETACHED}} 127 128This constructor creates a new detached (default) or joinable C++ thread object. It 129does not create or start execution of the real thread -- for this you should 130use the \helpref{Create}{wxthreadcreate} and \helpref{Run}{wxthreadrun} methods. 131 132The possible values for {\it kind} parameters are: 133 134\twocolwidtha{7cm} 135\begin{twocollist}\itemsep=0pt 136\twocolitem{{\bf wxTHREAD\_DETACHED}}{Creates a detached thread.} 137\twocolitem{{\bf wxTHREAD\_JOINABLE}}{Creates a joinable thread.} 138\end{twocollist} 139 140 141\membersection{wxThread::\destruct{wxThread}}\label{wxthreaddtor} 142 143\func{}{\destruct{wxThread}}{\void} 144 145The destructor frees the resources associated with the thread. Notice that you 146should never delete a detached thread -- you may only call 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 151Joinable threads should be deleted explicitly. The \helpref{Delete}{wxthreaddelete} and \helpref{Kill}{wxthreadkill} functions 152will not delete the C++ thread object. It is also safe to allocate them on 153stack. 154 155 156\membersection{wxThread::Create}\label{wxthreadcreate} 157 158\func{wxThreadError}{Create}{\param{unsigned int }{stackSize = 0}} 159 160Creates a new thread. The thread object is created in the suspended state, and you 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 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. 166 167{\bf Warning:} It is a good idea to explicitly specify a value as systems' 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 177thread. 178 179 180\wxheading{Return value} 181 182One of: 183 184\twocolwidtha{7cm} 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.} 189\end{twocollist} 190 191 192\membersection{wxThread::Delete}\label{wxthreaddelete} 193 194\func{wxThreadError}{Delete}{\void} 195 196Calling \helpref{Delete}{wxthreaddelete} gracefully terminates a 197detached thread, either when the thread calls \helpref{TestDestroy}{wxthreadtestdestroy} or finished processing. 198 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). 202 203See \helpref{wxThread deletion}{deletionwxthread} for a broader explanation of this routine. 204 205%%FIXME: What does this return and why? 206 207\membersection{wxThread::Entry}\label{wxthreadentry} 208 209\func{virtual ExitCode}{Entry}{\void} 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 214The returned value is the thread exit code which is only useful for 215joinable threads and is the value returned by \helpref{Wait}{wxthreadwait}. 216 217This function is called by wxWidgets itself and should never be called 218directly. 219 220 221\membersection{wxThread::Exit}\label{wxthreadexit} 222 223\func{void}{Exit}{\param{ExitCode }{exitcode = 0}} 224 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 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 230execution) and also delete the associated C++ object for detached threads. 231\helpref{wxThread::OnExit}{wxthreadonexit} will be called just before exiting. 232 233 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 244 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 253 254\membersection{wxThread::GetId}\label{wxthreadgetid} 255 256\constfunc{unsigned long}{GetId}{\void} 257 258Gets the thread identifier: this is a platform dependent number that uniquely identifies the 259thread throughout the system during its existence (i.e. the thread identifiers may be reused). 260 261 262\membersection{wxThread::GetPriority}\label{wxthreadgetpriority} 263 264\constfunc{int}{GetPriority}{\void} 265 266Gets the priority of the thread, between zero and 100. 267 268The following priorities are defined: 269 270\twocolwidtha{7cm} 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} 275\end{twocollist} 276 277 278\membersection{wxThread::IsAlive}\label{wxthreadisalive} 279 280\constfunc{bool}{IsAlive}{\void} 281 282Returns \true if the thread is alive (i.e. started and not terminating). 283 284Note that this function can only safely be used with joinable threads, not 285detached ones as the latter delete themselves and so when the real thread is 286no longer alive, it is not possible to call this function because 287the wxThread object no longer exists. 288 289\membersection{wxThread::IsDetached}\label{wxthreadisdetached} 290 291\constfunc{bool}{IsDetached}{\void} 292 293Returns \true if the thread is of the detached kind, \false if it is a joinable 294one. 295 296 297\membersection{wxThread::IsMain}\label{wxthreadismain} 298 299\func{static bool}{IsMain}{\void} 300 301Returns \true if the calling thread is the main application thread. 302 303 304\membersection{wxThread::IsPaused}\label{wxthreadispaused} 305 306\constfunc{bool}{IsPaused}{\void} 307 308Returns \true if the thread is paused. 309 310 311\membersection{wxThread::IsRunning}\label{wxthreadisrunning} 312 313\constfunc{bool}{IsRunning}{\void} 314 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 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 328may become inconsistent. Use \helpref{Delete()}{wxthreaddelete} for detached 329threads or \helpref{Wait()}{wxthreadwait} for joinable threads instead. 330 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 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. 336 337This function can only be called from another thread context, i.e. a thread 338cannot kill itself. 339 340It is also an error to call this function for a thread which is not running or 341paused (in the latter case, the thread will be resumed first) -- if you do it, 342a {\tt wxTHREAD\_NOT\_RUNNING} error will be returned. 343 344 345\membersection{wxThread::OnExit}\label{wxthreadonexit} 346 347\func{void}{OnExit}{\void} 348 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 351thread. This function will not be called if the thread was 352\helpref{killed}{wxthreadkill}. 353 354This function should never be called directly. 355 356 357\membersection{wxThread::Pause}\label{wxthreadpause} 358 359\func{wxThreadError}{Pause}{\void} 360 361Suspends the thread. Under some implementations (Win32), the thread is 362suspended immediately, under others it will only be suspended when it calls 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 368 369\membersection{wxThread::Run}\label{wxthreadrun} 370 371\func{wxThreadError}{Run}{\void} 372 373Starts the thread execution. Should be called after 374\helpref{Create}{wxthreadcreate}. 375 376This function can only be called from another thread context. 377 378 379\membersection{wxThread::SetPriority}\label{wxthreadsetpriority} 380 381\func{void}{SetPriority}{\param{int}{ priority}} 382 383Sets the priority of the thread, between $0$ and $100$. It can only be set 384after calling \helpref{Create()}{wxthreadcreate} but before calling 385\helpref{Run()}{wxthreadrun}. 386 387The following priorities are already defined: 388 389\twocolwidtha{7cm} 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} 394\end{twocollist} 395 396 397\membersection{wxThread::Sleep}\label{wxthreadsleep} 398 399\func{static void}{Sleep}{\param{unsigned long }{milliseconds}} 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 404threads (i.e. all except the main one). 405 406 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 415 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 424Returns \true on success or false otherwise (for example, if this function is 425not implemented for this platform -- currently everything except Solaris). 426 427 428\membersection{wxThread::TestDestroy}\label{wxthreadtestdestroy} 429 430\func{virtual bool}{TestDestroy}{\void} 431 432This function should be called periodically by the thread to ensure that calls 433to \helpref{Pause}{wxthreadpause} and \helpref{Delete}{wxthreaddelete} will 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. 439 440 441\membersection{wxThread::This}\label{wxthreadthis} 442 443\func{static wxThread *}{This}{\void} 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 448not created with wxThread class. Generally speaking, the return value for such a thread 449is undefined. 450 451 452\membersection{wxThread::Yield}\label{wxthreadyield} 453 454\func{void}{Yield}{\void} 455 456Give the rest of the thread time slice to the system allowing the other threads to run. 457See also \helpref{Sleep()}{wxthreadsleep}. 458 459 460\membersection{wxThread::Wait}\label{wxthreadwait} 461 462\constfunc{ExitCode}{Wait}{\void} 463 464Waits for a joinable thread to terminate and returns the value the thread 465returned from \helpref{wxThread::Entry}{wxthreadentry} or {\tt (ExitCode)-1} on 466error. Notice that, unlike \helpref{Delete}{wxthreaddelete} doesn't cancel the 467thread in any way so the caller waits for as long as it takes to the thread to 468exit. 469 470You can only Wait() for joinable (not detached) threads. 471 472This function can only be called from another thread context. 473 474See \helpref{wxThread deletion}{deletionwxthread} for a broader explanation of this routine. 475 476