c# – 线程缓慢且难以预测?

前端之家收集整理的这篇文章主要介绍了c# – 线程缓慢且难以预测?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经创建了光线跟踪器的基础,这是我绘制场景的测试函数
public void Trace(int start,int jump,Sphere testSphere)
{
    for (int x = start; x < scene.SceneWidth; x += jump)
    {
        for (int y = 0; y < scene.SceneHeight; y++)
        {
            Ray fired = Ray.FireThroughPixel(scene,x,y);

            if (testSphere.Intersects(fired))
                sceneRenderer.SetPixel(x,y,Color.Red);
            else sceneRenderer.SetPixel(x,Color.Black);
        }
    }
}

SetPixel只是在一维颜色数组中设置一个值.如果我通过直接调用它来正常调用函数它以恒定的55fps运行.如果我做:

Thread t1 = new Thread(() => Trace(0,1,testSphere));
t1.Start();
t1.Join();

它以50fps的速度运行,这很好并且可以理解,但是当我这样做时:

Thread t1 = new Thread(() => Trace(0,2,testSphere));
Thread t2 = new Thread(() => Trace(1,testSphere));

t1.Start();
t2.Start();

t1.Join();
t2.Join();

它遍布整个地方,在30-40 fps之间快速移动,有时超出50或者降到20,它根本不是恒定的.为什么它比在单个线程上运行整个事情时运行速度慢?我正在运行四核i5 2500k.

解决方法

如果没有分析您的应用程序,这很难回答,但我会怀疑虚假分享.

两个线程都写入共享内存结构,这将导致cpu缓存保持无效.

测试的简便方法是为每个线程创建一个单独的输出数组.

它不必工作 – 只需看看帧速率.

我前段时间写了一篇关于此的文章:“Concurrency Hazards: False Sharing

猜你在找的C#相关文章