-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathFrameAndThread.cpp
59 lines (51 loc) · 1.71 KB
/
FrameAndThread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <wx/wx.h>
#include <thread>
using namespace std;
namespace FrameAndThreadExample {
class thread_state {
public:
int userThreadId = -1;
int counter = 0;
};
class Frame : public wxFrame {
public:
Frame() : wxFrame(nullptr, wxID_ANY, "Frame and thread example") {
Bind(wxEVT_THREAD, [&](wxThreadEvent& event) {
auto state = event.GetPayload<thread_state>();
listBox->Append(wxString::Format("thread: %d, counter: %d", state.userThreadId, state.counter));
listBox->SetSelection(listBox->GetCount() - 1);
});
Bind(wxEVT_CLOSE_WINDOW, [&](wxCloseEvent& event) {
closed = true;
for (auto index = 0; index < threads.size(); index++)
threads[index].join();
event.Veto(false);
event.Skip(true);
});
threads = vector<thread>(thread::hardware_concurrency());
for (auto index = 0; index < threads.size(); index++) {
threads[index] = thread([&](int userThreadId) {
thread_state state;
state.userThreadId = userThreadId;
while (!closed) {
/// simulate work...
wxMilliSleep(50);
state.counter++;
/// call QueueEvent method to send event to the main thread.
wxThreadEvent* event = new wxThreadEvent(wxEVT_THREAD);
event->SetPayload(state);
QueueEvent(event);
}
}, index);
}
}
private:
wxListBox* listBox = new wxListBox(this, wxID_ANY);
bool closed = false;
vector<thread> threads;
};
class Application : public wxApp {
bool OnInit() override {return (new Frame)->Show();}
};
}
wxIMPLEMENT_APP(FrameAndThreadExample::Application);