threads in wxWidgets

gruber picture gruber · Jun 1, 2010 · Viewed 10k times · Source

Im using wxWidgets and I call function which takes a long time to proceed. I would like to do it in background.

How can I do that?

Thanks for help

Answer

Evan Cordell picture Evan Cordell · Jul 19, 2010

I've worked with threads in wxWidgets in pretty much all of the ways described here, and I can say that using custom events, while initially a bit more complex, saves you some headache in the long run. (The wxMessageQueue class is quite nice, but when I used it I found it to leak; I haven't checked it in about a year though.)

A basic example:

MyFrm.cpp

#include "MyThread.h"

BEGIN_EVENT_TABLE(MyFrm,wxFrame)
    EVT_COMMAND(wxID_ANY, wxEVT_MYTHREAD, MyFrm::OnMyThread)
END_EVENT_TABLE()
void MyFrm::PerformCalculation(int someParameter){
    //create the thread
    MyThread *thread = new Mythread(this, someParameter);
    thread->Create();
    thread->Run();
    //Don't worry about deleting the thread, there are two types of wxThreads 
    //and this kind deletes itself when it's finished.
}
void MyFrm::OnMyThread(wxCommandEvent& event)
{
    unsigned char* temp = (unsigned char*)event.GetClientData();
    //do something with temp, which holds unsigned char* data from the thread
    //GetClientData() can return any kind of data you want, but you have to cast it.
    delete[] temp; 
}    

MyThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <wx/thread.h>
#include <wx/event.h>

BEGIN_DECLARE_EVENT_TYPES()
    DECLARE_EVENT_TYPE(wxEVT_MYTHREAD, -1)
END_DECLARE_EVENT_TYPES()

class MyThread : public wxThread
{
    public:
        MyThread(wxEvtHandler* pParent, int param);
    private:
        int m_param;
        void* Entry();
    protected:
        wxEvtHandler* m_pParent;
};
#endif 

MyThread.cpp

#include "MyThread.h"
DEFINE_EVENT_TYPE(wxEVT_MYTHREAD)
MyThread::MyThread(wxEvtHandler* pParent, int param) : wxThread(wxTHREAD_DETACHED), m_pParent(pParent)
{
    //pass parameters into the thread
m_param = param;
}
void* MyThread::Entry()
{
    wxCommandEvent evt(wxEVT_MYTHREAD, GetId());
    //can be used to set some identifier for the data
    evt.SetInt(r); 
    //whatever data your thread calculated, to be returned to GUI
    evt.SetClientData(data); 
    wxPostEvent(m_pParent, evt);
    return 0;
}

I feel like this is much more clear, concise example than the one the wiki offers. Obviously I left out code concerning actually launching the app (wx convention would make that MyApp.cpp) and any other non-thread-related code.