Categories: ComponentswxWidgets

Реализация Job Queue на wxWidgets (+исходник)

При работе с потоками часто приходится делать кучу однотипных задач: создавать класс, производный от wxThread, реализовывать метод Entry() для этого класса, синхронизацию с главным потоком и т.д.

Eran, автор CodeLite IDE поделился кодом класса JobQueue, который реализует пул потоков и позволяет выполнять задачи в фоновом режиме.

class MyJob : public Job {
public:
        MyJob(){}
        ~MyJob(){}

        // Implement your processing code here
        void Process() {
                wxPrintf(wxT("Just doing my work...n"));
        };
};

// define some custom job with progress report
class MyJobWithProgress : public Job {
public:
        MyJobWithProgress(wxEvtHandler *parent) : Job(parent){}
        ~MyJobWithProgress(){}

        // Implement your processing code here
        void Process() {
                // report to parent that we are at stage 0
                Post(0, wxT("Stage Zero"));
                // do the work
                wxPrintf(wxT("Just doing my work...n"));
                // report to parent that we are at stage 1
                Post(1, wxT("Stage Zero Completed!"));
        };
};

// somewhere in your code, start the JobQueue
// for the demo we use pool of size 5
JobQueueSingleton::Instance()->Start(5);

// whenever you want to process MyJob(), just create new instance of MyJob() and add it to the JobQueue
JobQueueSingleton::Instance()->AddJob( new MyJob() );

// at shutdown stop the job queue and release all its resources
JobQueueSingleton::Instance()->Stop();
JobQueueSingleton::Release();

// OR, you can use JobQueue directly without the JobQueueSingleton wrapper class
// so you could have multiple instances of JobQueue

Главный поток получает уведомления таким вот образом:

// in the event table
EVT_COMMAND(wxID_ANY, wxEVT_CMD_JOB_STATUS, MyFrame::OnJobStatus)

void MyFrame::OnJobStatus(wxCommandEvent &e)
{
wxString msg;
msg << wxT("Job progress: Stage: ") << e.GetInt() << wxT(" Message: ") << e.GetString(); wxLogMessage(msg) } [/sourcecode] Скачать исходный код
Читать обсуждение на wxForum

T-Rex

Share
Published by
T-Rex

Recent Posts

Разработка кроссплатформенных модульных приложений на C++ с библиотекой wxWidgets

Введение Уже долгое время не пишу статьи о разработке, хотя сам процесс написания мне очень…

10 years ago

wxWidgets App With Plugins (Windows/Linux/Mac) – Sample Source Code

I can see that there is still a lot of topics at wxWidgets forums related…

11 years ago

wxToolBox is Now Open-Source!

I've just published the source code of wxToolBox component and a couple of sample apps at…

11 years ago

Microsoft Kinect Helper Library and Sample for wxWidgets

Microsoft released their Kinect SDK several days ago. So, for those wxWidgets developers who are…

13 years ago

wxJSON 1.1.0 Released

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to…

14 years ago

wxRuby. Оно даже работает!

Вдохновленнный читаемой нынче книгой My Job Went to India: 52 Ways to Save Your Job…

15 years ago