gpt4 book ai didi

c++ - GDI+ 多线程绘图

转载 作者:行者123 更新时间:2023-11-28 03:13:28 26 4
gpt4 key购买 nike

免责声明:在谈到多线程时,我有点菜鸟。我已经在线阅读资料,完成了一些简单的多线程示例。

我有一个 Win32 应用程序,它想在一个线程中绘制内容并在另一个线程中处理 Win32 消息。但是,在创建窗口并启动线程后,它挂起。我有一种预感,它可能与 WaitForMultipleObjects() 有关,但我不知道如何正确处理。有谁知道为什么会这样?我应该暂停和恢复线程吗?

这是我的代码:

WinAPI:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow)
{
/* initialization blah blah */

zgE->startThreads(); // <--- starts the 2 threads

WaitForMultipleObjects(zgE->getThreadsNo(), zgE->getThreads(), TRUE, INFINITE);
return TRUE;
}

这是我启动线程的方式:

void zgEngine::startThreads()
{
/* allocation and stuff, blah blah blah */

m_arrThreads[m_nThreads++] = CreateThread(NULL, 0, &zgEngine::handleMsg, (void*)this, NULL, NULL);
m_arrThreads[m_nThreads++] = CreateThread(NULL, 0, &zgEngine::drawObjects, (void*)this, NULL, NULL);

assert(m_nThreads <= THREADS_NO);
}

绘制和处理消息的 2 个函数非常简单。每个循环中都有一个 while 循环。

// draw function
DWORD WINAPI zgEngine::drawObjects(LPVOID lpParam)
{
while (true)
{
/* draw stuff - valid code that if called outside this function
works as intended */
}

return TRUE;
}

// message handler function
DWORD WINAPI zgEngine::handleMsg(LPVOID lpParam)
{
MSG msg;
while (true)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Process the message
if (msg.message == WM_QUIT)
break;

TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

return TRUE;
}

当我不使用线程并删除 drawObjects() 中的“while (true)”,但保留代码(只执行一次)时,不要调用 handleMsg() 并使 WinMain 像在下面的示例中,它就像一个魅力。

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow)
{
/* initialization blah blah */

MSG msg;
while (true)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Process the message
if (msg.message == WM_QUIT)
break;

TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
zgEngine::DrawObjects(zgE);
}
}
return TRUE;
}

稍后编辑:据我所见,PeekMessage() 总是返回 0 :(

最佳答案

引自 PeekMessage在 Microsoft 的网站上:

A handle to the window whose messages are to be retrieved. The window must belong to the current thread.

If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.

If hWnd is -1, PeekMessage retrieves only messages on the current thread's message queue whose hwnd value is NULL, that is, thread messages as posted by PostMessage (when the hWnd parameter is NULL) or PostThreadMessage.

我怀疑该线程没有“当前窗口”,并且“当前线程消息队列”不是 Windows 实际将消息发布到的默认线程。这只是一个假设,因为您的方法完全有可能存在其他问题(以及?)。但我相信这是问题所在的主要部分。

关于c++ - GDI+ 多线程绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17676991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com