我正在使用 C++ 在 WM_PAINT 事件中绘制多边形 (Polygon(dc, points, 3))。我有大量的多边形,所以我正在尝试实现多线程。我正在运行 VS2013,所以我包含了线程。我创建了一个要在线程上运行的函数:
void anyFunс2(HDC dc, int index)
{
POINT points[3];
for (unsigned i = index; i < model->vertexFaces.size(); i += fs)
{
// Here we convert our points to Clip and Windowed Coordinates
// and only then fetch the results
if (Algorithms::FetchPolygons(&model->finalizedVertices[0], model->vertexFaces[i], points))
{
Polygon(dc, points, 3);
}
}
}
例如我有三个线程。我将代码设计为每个线程呈现每个第三个元素的方式。例如,第一个线程渲染 0,3,6,9 个多边形,第二个线程渲染 1,4,7,10,最后一个线程渲染 2,5,8,11 个多边形。
这是我的 WM_PAINT 事件:
case WM_PAINT:
{
// Get dc here
hdc = GetDC(hWnd);
// Create a backbuffer here
bdc = CreateCompatibleDC(hdc);
// Get the screen dimensions
RECT client;
GetClientRect(hWnd, &client);
// Create bitmap
HBITMAP backBuffer = CreateCompatibleBitmap(hdc, client.right - client.left, client.bottom - client.top);
// Release it, because we no longer need it
hdc = NULL;
ReleaseDC(hWnd, hdc);
// Select the back dc as a current one and specify the screen dimensions
HPEN hPen = CreatePen(PS_SOLID, 1, RGB(0, 25, 205));
HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 55));
SelectObject(bdc, hPen);
SelectObject(bdc, hBrush);
SelectObject(bdc, backBuffer);
Rectangle(bdc, client.left, client.top, client.right, client.bottom);
// Call some threads to draw polygons on our BDC
for (unsigned i = 0; i < func_threads.size(); i++)
{
func_threads.at(i) = thread(anyFunс2, bdc, i);
}
// Wait until all threads finish their job
for (unsigned i = 0; i < func_threads.size(); i++)
{
if (func_threads[i].joinable()) func_threads[i].join();
}
// Swap buffers
hdc = BeginPaint(hWnd, &ps);
BitBlt(hdc, client.left, client.top, client.right, client.bottom, bdc, 0, 0, SRCCOPY);
EndPaint(hWnd, &ps);
// Delete all created objects from memory
DeleteObject(backBuffer);
DeleteObject(hBrush);
DeleteObject(hPen);
DeleteDC(bdc);
break;
}
如您所见,我在循环中运行这些线程。然后我有另一个循环,每个线程的 Join() 方法都位于其中。这些线程将多边形绘制到同一个 HDC(我假设)。在主线程完成等待所有这些线程后,它会将后台缓冲区中的所有内容复制到主线程。但是问题是对象没有完全绘制。我的意思是不是所有的多边形都被绘制出来。图片的链接附在此处。请帮助我,为什么会这样?!