我正在用 Java 编写一个光线追踪程序,并使用 Runnable 接口实现了多线程。每个线程渲染 800 条垂直线的一部分。当使用两个线程时,每个线程将渲染 400 行。对于 8 个线程,每个线程 100 行,依此类推。
我的解决方案目前正在运行,但是当更多线程并行工作时,渲染时间不会减少。我的 CPU 有 8 个线程,在 8 个线程上渲染时使用率不是 100%。
class Multithread implements Runnable {
Camera camera;
CountDownLatch latch;
...
//Constructor for thread
Multithread(Scene s, Camera c, int thread, int threadcount, CountDownLatch cdl){
camera = c;
latch = cdl;
...
}
public void run(){
try{
...
//This is the render function
camera.render(...);
//When all threads unlatch, main class will write PNG
latch.countDown();
}
catch (Exception e){System.out.println ("Exception is caught");}
}
}
public class Camera {
//The final pixel values are stored in the 2D-array
ColorDbl[][] finalImage;
Camera(int w){
Width = w;
finalImage = new ColorDbl[w][w]
}
//Start rendering
void render(Scene S, int start, int end){
//Create temporary, partial image
ColorDbl[][] tempImage = new ColorDbl[Width][Width];
Ray r;
ColorDbl temp;
//Render lines of pixels in the interval start-end
for(int j = start; j < end; ++j){
for(int i = 0; i < Width; ++i){
r = new Ray(...);
temp = r.CastRay(...);
tempImage[i][j] = temp;
}
}
//Copy rendered lines to final image
for(int j=start; j<end; ++j){
for(int i=0; i<Width; ++i){
finalImage[i][j] = tempImage[i][j];
}
}
}
public static void main(String[] args) throws IOException{
//Create camera and scene
Camera camera = new Camera(800);
Scene scene = new Scene();
//Create threads
int threadcount = 4;
CountDownLatch latch = new CountDownLatch(threadcount);
for (int thread=0; thread<threadcount; thread++){
new Thread(new Multithread(scene, camera, thread, threadcount, latch)).start();
}
//Wait for threads to finish
try{
latch.await();
}catch(InterruptedException e){System.out.println ("Exception");}
//Write PNG
c.write(...);
}
}
当使用 2 个线程而不是 1 个线程时,我希望渲染速度几乎翻倍,但相反,它需要 50% 的时间。我不指望有人能解决我的问题,但在实现多线程时,我真的很感激一些指导。我会以错误的方式解决这个问题吗?