I have two static methods:
bool getPicture(const std::string url, const std::string keywords ="")
bool showPicture(wxStaticBitmap *viewer)
Those methods each one does a separate task, so, I want each one to be executed in a separate thread.
#include <wx/thread.h>
// Declaration
class CThread : public wxThread {
public:
CThread() = default;
~CThread() = default;
void *Entry();
};
// Implementation
void* CThread::Entry() {
CPublic::getPicture(mainFrm::getInstance()->targetURL, CPublic::getConfigItem("settings/keywords").ToStdString());
// CPublic::showPicture(mainFrm::getInstance()->viewer_btmp);
return 0;
}
// Create an instance
wxThread *th = new CThread();
th->Create();
th->Run();
As you seen in the previous code, there's one an Entry()
method in each thread class, so, I want another an Entry()
method to put my next method showPicture()
into it.
Do I have to create another class which has another Entry()
method to put my showPicture()
method into it, to be executed in another separate thread or there's another way?
Quick answer:
All instances of a class (wxThread is a class) share its methods. So if you want a different Entry()
, you need a new wxThread-derived class.
Advice on multithreading:
While getPicture()
can be executed in a secondary thread, showPicture()
should be executed in the main thread because it's the right place to draw into the window. All GUI stuff is strongly recommended to be done only in the main thread.
A rare expection is using OpenGL in a secondary thread instead of drawing by OS commands.
The point is that the secondary thread posts a message to the main thread telling "I'm done, image is available".
The new data (image processed) can be put in a placement where the main thread (e.g. the window that is going to draw it) can read it.
Prevent any other thread from accessing the data while the working thread (that for getPicture()
) is writting, by using wxCriticalSectionLocker
.
More info at wxWidgets docs, more wxWidgets doc an the thread
sample provided with wxWidgets distribution.