Raytracer Multithreading

I was given the task of optimising a basic raytracer, the only requirement was that it used multithreading. While there are many ways we could have optimised the raytracer the limited amount of time meant that almost only multithreading was used to optimise the raytracer.

The raytracer we were given used a simple for loop to look over every pixel of the screen and raycasting through to discover what color to give that pixel. It did all of these on one thread which tool a lot longer than it could have. On average it took about 46 seconds to complete the basic scene we were given. It had a numerical display at the top which showed us how long it took to complete the raytracing of the scene.

Before I started looking into raytracing I came up with something else to slightly optimise the raytracer. This occurred when we were looking through the raytracers code as a class. I saw that the raytracing section was checking the background images color even if it didn’t need to, and so the first thing I did to optimise was to move that code to after checking if the raycast hit a target so it only got ran if the raycast missed and it needed to use the background image color. This cut about half a second off of the raytracer time.

With that slight bit of optimisation complete I started to look into multithreading with the c++ Poco library. Setting up Poco was the most difficult part of this project as we had not compiled libraries before and ended up having to go through the process of setting it up as a class.

With the Poco Libraries imported I could start looking at implementing multithreading. First things first is to include the header files and make some threads:threading 1.PNG

No issues there. The next step of actually starting the threads is where I first came up on some issues. Immediately I saw two options Start() which takes a Poco::Runnable or StartFunc() which takes a functor. My first instict was to simply use StartFunc and separate the raytracing into a function, but I ran into issues figuring out how to use that with a function that has parameters, so I went looking at the Poco documentation and found that creating a class that inherits from runnable would be a lot closer to what I needed to do.

Threading 3.PNG

With that implemented I could use start on my threads to get them going simultaneously. Giving me a Raytracer that ran in 11 seconds instead of 46 and a lot of knowledge about multithreading to use in future projects.

Leave a comment