contents up previous next

wxthread

a thread is basically a path of execution through a program. threads are sometimes called light-weight processes, but the fundamental difference between threads and processes is that memory spaces of different processes are separated while all threads share the same address space.

while it makes it much easier to share common data between several threads, it also makes it much easier to shoot oneself in the foot, so careful use of synchronization objects such as mutexes or critical sections is recommended. in addition, don't create global thread objects because they allocate memory in their constructor, which will cause problems for the memory checking system.

derived from

none.

include files

<wx/thread.h>

see also

wxmutex, wxcondition, wxcriticalsection

members

types of wxthreads
wxthread deletion
wxwidgets calls in secondary threads
don't poll a wxthread
wxthread::wxthread
wxthread::~wxthread
wxthread::create
wxthread::delete
wxthread::entry
wxthread::exit
wxthread::getcpucount
wxthread::getcurrentid
wxthread::getid
wxthread::getpriority
wxthread::isalive
wxthread::isdetached
wxthread::ismain
wxthread::ispaused
wxthread::isrunning
wxthread::kill
wxthread::onexit
wxthread::pause
wxthread::run
wxthread::setpriority
wxthread::sleep
wxthread::resume
wxthread::setconcurrency
wxthread::testdestroy
wxthread::this
wxthread::yield
wxthread::wait


types of wxthreads

there are two types of threads in wxwidgets: detached and joinable, modeled after the the posix thread api. this is different from the win32 api where all threads are joinable.

by default wxthreads in wxwidgets use the detached behavior. detached threads delete themselves once they have completed, either by themselves when they complete processing or through a call to wxthread::delete, and thus must be created on the heap (through the new operator, for example). conversely, joinable threads do not delete themselves when they are done processing and as such are safe to create on the stack. joinable threads also provide the ability for one to get value it returned from wxthread::entry through wxthread::wait.

you shouldn't hurry to create all the threads joinable, however, because this has a disadvantage as well: you must wait() for a joinable thread or the system resources used by it will never be freed, and you also must delete the corresponding wxthread object yourself if you did not create it on the stack. in contrast, detached threads are of the "fire-and-forget" kind: you only have to start a detached thread and it will terminate and destroy itself.


wxthread deletion

regardless of whether it has terminated or not, you should call wxthread::wait on a joinable thread to release its memory, as outlined in types of wxthreads. if you created a joinable thread on the heap, remember to delete it manually with the delete operator or similar means as only detached threads handle this type of memory management.

since detached threads delete themselves when they are finished processing, you should take care when calling a routine on one. if you are certain the thread is still running and would like to end it, you may call wxthread::delete to gracefully end it (which implies that the thread will be deleted after that call to delete()). it should be implied that you should never attempt to delete a detached thread with the delete operator or similar means.

as mentioned, wxthread::wait or wxthread::delete attempts to gracefully terminate a joinable and detached thread, respectively. it does this by waiting until the thread in question calls wxthread::testdestroy or ends processing (returns from wxthread::entry).

obviously, if the thread does call testdestroy() and does not end the calling thread will come to halt. this is why it is important to call testdestroy() in the entry() routine of your threads as often as possible.

as a last resort you can end the thread immediately through wxthread::kill. it is strongly recommended that you do not do this, however, as it does not free the resources associated with the object (although the wxthread object of detached threads will still be deleted) and could leave the c runtime library in an undefined state.


wxwidgets calls in secondary threads

all threads other then the "main application thread" (the one wxapp::oninit or your main function runs in, for example) are considered "secondary threads". these include all threads created by wxthread::create or the corresponding constructors.

gui calls, such as those to a wxwindow or wxbitmap are explicitly not safe at all in secondary threads and could end your application prematurely. this is due to several reasons, including the underlying native api and the fact that wxthread does not run a gui event loop similar to other apis as mfc.

a workaround that works on some wxwidgets ports is calling wxmutexguienter before any gui calls and then calling wxmutexguileave afterwords. however, the recommended way is to simply process the gui calls in the main thread through an event that is posted by either wxpostevent or wxevthandler::addpendingevent. this does not imply that calls to these classes are thread-safe, however, as most wxwidgets classes are not thread-safe, including wxstring.


don't poll a wxthread

a common problem users experience with wxthread is that in their main thread they will check the thread every now and then to see if it has ended through wxthread::isrunning, only to find that their application has run into problems because the thread is using the default behavior and has already deleted itself. naturally, they instead attempt to use joinable threads in place of the previous behavior.

however, polling a wxthread for when it has ended is in general a bad idea - in fact calling a routine on any running wxthread should be avoided if possible. instead, find a way to notify yourself when the thread has ended. usually you only need to notify the main thread, in which case you can post an event to it via wxpostevent or wxevthandler::addpendingevent. in the case of secondary threads you can call a routine of another class when the thread is about to complete processing and/or set the value of a variable, possibly using mutexes and/or other synchronization means if necessary.


wxthread::wxthread

wxthread(wxthreadkind kind = wxthread_detached)

this constructor creates a new detached (default) or joinable c++ thread object. it does not create or start execution of the real thread -- for this you should use the create and run methods.

the possible values for kind parameters are:

wxthread_detached creates a detached thread.
wxthread_joinable creates a joinable thread.


wxthread::~wxthread

~wxthread()

the destructor frees the resources associated with the thread. notice that you should never delete a detached thread -- you may only call delete on it or wait until it terminates (and auto destructs) itself. because the detached threads delete themselves, they can only be allocated on the heap.

joinable threads should be deleted explicitly. the delete and kill functions will not delete the c++ thread object. it is also safe to allocate them on stack.


wxthread::create

wxthreaderror create(unsigned int stacksize = 0)

creates a new thread. the thread object is created in the suspended state, and you should call run to start running it. you may optionally specify the stack size to be allocated to it (ignored on platforms that don't support setting it explicitly, eg. unix system without pthread_attr_setstacksize). if you do not specify the stack size, the system's default value is used.

warning: it is a good idea to explicitly specify a value as systems' default values vary from just a couple of kb on some systems (bsd and os/2 systems) to one or several mb (windows, solaris, linux). so, if you have a thread that requires more than just a few kb of memory, you will have mysterious problems on some platforms but not on the common ones. on the other hand, just indicating a large stack size by default will give you performance issues on those systems with small default stack since those typically use fully committed memory for the stack. on the contrary, if use a lot of threads (say several hundred), virtual adress space can get tight unless you explicitly specify a smaller amount of thread stack space for each thread.

return value

one of:

wxthread_no_error there was no error.
wxthread_no_resource there were insufficient resources to create a new thread.
wxthread_running the thread is already running.


wxthread::delete

wxthreaderror delete()

calling delete gracefully terminates a detached thread, either when the thread calls testdestroy or finished processing.

(note that while this could work on a joinable thread you simply should not call this routine on one as afterwards you may not be able to call wxthread::wait to free the memory of that thread).

see wxthread deletion for a broader explanation of this routine.


wxthread::entry

virtual exitcode entry()

this is the entry point of the thread. this function is pure virtual and must be implemented by any derived class. the thread execution will start here.

the returned value is the thread exit code which is only useful for joinable threads and is the value returned by wait.

this function is called by wxwidgets itself and should never be called directly.


wxthread::exit

void exit(exitcode exitcode = 0)

this is a protected function of the wxthread class and thus can only be called from a derived class. it also can only be called in the context of this thread, i.e. a thread can only exit from itself, not from another thread.

this function will terminate the os thread (i.e. stop the associated path of execution) and also delete the associated c++ object for detached threads. wxthread::onexit will be called just before exiting.


wxthread::getcpucount

static int getcpucount()

returns the number of system cpus or -1 if the value is unknown.

see also

setconcurrency


wxthread::getcurrentid

static unsigned long getcurrentid()

returns the platform specific thread id of the current thread as a long. this can be used to uniquely identify threads, even if they are not wxthreads.


wxthread::getid

unsigned long getid() const

gets the thread identifier: this is a platform dependent number that uniquely identifies the thread throughout the system during its existence (i.e. the thread identifiers may be reused).


wxthread::getpriority

int getpriority() const

gets the priority of the thread, between zero and 100.

the following priorities are defined:

wxthread_min_priority 0
wxthread_default_priority 50
wxthread_max_priority 100


wxthread::isalive

bool isalive() const

returns true if the thread is alive (i.e. started and not terminating).

note that this function can only safely be used with joinable threads, not detached ones as the latter delete themselves and so when the real thread is no longer alive, it is not possible to call this function because the wxthread object no longer exists.


wxthread::isdetached

bool isdetached() const

returns true if the thread is of the detached kind, false if it is a joinable one.


wxthread::ismain

static bool ismain()

returns true if the calling thread is the main application thread.


wxthread::ispaused

bool ispaused() const

returns true if the thread is paused.


wxthread::isrunning

bool isrunning() const

returns true if the thread is running.

this method may only be safely used for joinable threads, see the remark in isalive.


wxthread::kill

wxthreaderror kill()

immediately terminates the target thread. this function is dangerous and should be used with extreme care (and not used at all whenever possible)! the resources allocated to the thread will not be freed and the state of the c runtime library may become inconsistent. use delete() for detached threads or wait() for joinable threads instead.

for detached threads kill() will also delete the associated c++ object. however this will not happen for joinable threads and this means that you will still have to delete the wxthread object yourself to avoid memory leaks. in neither case onexit of the dying thread will be called, so no thread-specific cleanup will be performed.

this function can only be called from another thread context, i.e. a thread cannot kill itself.

it is also an error to call this function for a thread which is not running or paused (in the latter case, the thread will be resumed first) -- if you do it, a wxthread_not_running error will be returned.


wxthread::onexit

void onexit()

called when the thread exits. this function is called in the context of the thread associated with the wxthread object, not in the context of the main thread. this function will not be called if the thread was killed.

this function should never be called directly.


wxthread::pause

wxthreaderror pause()

suspends the thread. under some implementations (win32), the thread is suspended immediately, under others it will only be suspended when it calls testdestroy for the next time (hence, if the thread doesn't call it at all, it won't be suspended).

this function can only be called from another thread context.


wxthread::run

wxthreaderror run()

starts the thread execution. should be called after create.

this function can only be called from another thread context.


wxthread::setpriority

void setpriority(int priority)

sets the priority of the thread, between 0 and 100. it can only be set after calling create() but before calling run().

the following priorities are already defined:

wxthread_min_priority 0
wxthread_default_priority 50
wxthread_max_priority 100


wxthread::sleep

static void sleep(unsigned long milliseconds)

pauses the thread execution for the given amount of time.

this function should be used instead of wxsleep by all worker threads (i.e. all except the main one).


wxthread::resume

wxthreaderror resume()

resumes a thread suspended by the call to pause.

this function can only be called from another thread context.


wxthread::setconcurrency

static bool setconcurrency(size_t level)

sets the thread concurrency level for this process. this is, roughly, the number of threads that the system tries to schedule to run in parallel. the value of 0 for level may be used to set the default one.

returns true on success or false otherwise (for example, if this function is not implemented for this platform -- currently everything except solaris).


wxthread::testdestroy

virtual bool testdestroy()

this function should be called periodically by the thread to ensure that calls to pause and delete will work. if it returns true, the thread should exit as soon as possible.

notice that under some platforms (posix), implementation of pause also relies on this function being called, so not calling it would prevent both stopping and suspending thread from working.


wxthread::this

static wxthread * this()

return the thread object for the calling thread. null is returned if the calling thread is the main (gui) thread, but ismain should be used to test whether the thread is really the main one because null may also be returned for the thread not created with wxthread class. generally speaking, the return value for such a thread is undefined.


wxthread::yield

void yield()

give the rest of the thread time slice to the system allowing the other threads to run. see also sleep().


wxthread::wait

exitcode wait() const

waits for a joinable thread to terminate and returns the value the thread returned from wxthread::entry or (exitcode)-1 on error. notice that, unlike delete doesn't cancel the thread in any way so the caller waits for as long as it takes to the thread to exit.

you can only wait() for joinable (not detached) threads.

this function can only be called from another thread context.

see wxthread deletion for a broader explanation of this routine.