一个消息循环做的并行类。
class ClsA { public: ClsA(); LRESULT HandleMessage(HWND, UINT, WPARAM, LPARAM); void Method1(); public: static LPCTSTR WindowClass; static ATOM RegisterWndClass(HINSTANCE hInst); public: static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); HWND m_hWnd; UINT32 m_val; }; ClsA::ClsA() { // 创建一个MessageOnly窗口 m_hWnd = CreateWindow(WindowClass, NULL, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, HWND_MESSAGE, NULL, NULL, (LPVOID)this); m_val = 0; } void ClsA::Method1() { ATLTRACE(_T("%u\n"), m_val); ++m_val; } LRESULT ClsA::HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_APP + 1: Method1(); break; default: return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } LPCTSTR ClsA::WindowClass = _T("ClsAWindowClass"); ATOM ClsA::RegisterWndClass(HINSTANCE hInst) { WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ClsA::WndProc; wcex.hInstance = hInst; wcex.lpszClassName = ClsA::WindowClass; return RegisterClassEx(&wcex); } LRESULT CALLBACK ClsA::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: { LPCREATESTRUCT lpCS = (LPCREATESTRUCT)lParam; SetWindowLong(hWnd, GWL_USERDATA, (LONG)lpCS->lpCreateParams); break; } default: ClsA* lpObj = (ClsA*)GetWindowLong(hWnd, GWL_USERDATA); if (nullptr != lpObj) { return lpObj->HandleMessage(hWnd, uMsg, wParam, lParam); } return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; }测试代码:
DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter) { HWND hWnd = (HWND)lpParameter; for (size_t i = 0; i < 1000; i++) { ::SendMessage(hWnd, WM_APP + 1, NULL, NULL); } return 0; } // 主线程逻辑 ClsA::RegisterWndClass(hInstance); ClsA a; CreateThread(nullptr, 0, ThreadProc, a.m_hWnd, 0, nullptr); CreateThread(nullptr, 0, ThreadProc, a.m_hWnd, 0, nullptr); // 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }