我已经使用wxWidgets中的线程处理了几乎所有这里描述的方式,我可以说使用自定义事件,虽然最初有点复杂,但从长远来看会让你头疼.(wxMessageQueue类非常好,但是当我使用它时,我发现它泄漏了;虽然我在大约一年内没有检查过它.)
一个基本的例子:
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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我觉得这比wiki提供的更加清晰,简洁.显然,我遗漏了有关实际启动应用程序的代码(wx约定会使MyApp.cpp)以及任何其他非线程相关的代码.
如果你只是需要让一些东西在后台工作直到它完成——如果你愿意的话,就可以忘记,像这样:
// warning: off the top of my head ;-)
class MyThread
: public wxThread
{
public:
MyThread() : wxThread(wxTHREAD_DETACHED)
{
if(wxTHREAD_NO_ERROR == Create()) {
Run();
}
}
protected:
virtual ExitCode Entry()
{
// do something here that takes a long time
// it's a good idea to periodically check TestDestroy()
while(!TestDestroy() && MoreWorkToDo()) {
DoSaidWork();
}
return static_cast<ExitCode>(NULL);
}
};
MyThread* thd = new MyThread(); // auto runs & deletes itself when finished
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9264 次 |
| 最近记录: |