You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于SetPixel()线程安全性与Mandelbrot集渲染优化的技术问询

原问题

我正使用VS 2022社区版实现Mandelbrot集,通过二维循环计算并调用SetPixel()渲染,虽可正常运行但耗时7秒,希望优化速度。考虑将图像分块后用多线程处理,但需明确SetPixel()是否线程安全——若线程处理不同区域,并发调用是否可行?用互斥锁控制SetPixel()访问是否合理?另一种方案是LockBits,不少帖子提及SetPixel()速度慢,建议使用LockBits,但我无法找到系统对LockBits的支持,也未找到完整实现方法。附原代码:

case WM_PAINT:
    {
    if (bHoldPaint) break;

        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);

        RECT rect;
        GetClientRect(hWnd, &rect);

        // Algorithm obtained from https://en.wikipedia.org/wiki/Mandelbrot_set.

        double x0, y0, x, y, xtemp;
        
        const int max_iterations = 1000;
        int iteration;
        
        int xPixel, yPixel;

        for (yPixel = rect.top; yPixel < rect.bottom; ++yPixel)
        {
            for (xPixel = rect.left; xPixel < rect.right; ++xPixel)
            {
                x0 = (xMax - xMin) / (rect.right - rect.left) * xPixel + xMin;
                y0 = (yMax - yMin) / (rect.bottom - rect.top) * yPixel + yMin;

                x = 0.0;
                y = 0.0;
                
                iteration = 0;
                
                while (x * x + y * y <= 2 * 2 && iteration < max_iterations)
                {
                    xtemp = x * x - y * y + x0;
                    y = 2 * x * y + y0;
                    x = xtemp;
                    ++iteration;
                }
                SetPixel(hdc, xPixel, yPixel, (COLORREF)(-16777215.0 / max_iterations * iteration + 16777215.0));
            }
        }

        EndPaint(hWnd, &ps);
    }
    break;
更新说明

最终我重新设计了程序:将工作负载拆分为5000个分片,通过FIFO分发至含64个线程的线程池,各线程竞争获取任务;同时操作内存位图而非调用SetPixel(),待所有线程完成后再绘制至DC,此方案响应时间为200-300毫秒。新代码已上传至GitHub。感谢各位协助!


内容的提问来源于stack exchange,提问作者Alex Sokolek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:04:54