Jean Valjean
Jean Valjean

Reputation: 736

Java: Multi-Threading and 2D threads

I'm making a ray-tracer that works but doesn't have lighting (yet). For those who don't know, ray-tracers work by sending out rays from the camera (the viewer) through each pixel of the screen, testing for collisions of objects in 3D space, and coloring the pixel if the ray hits an object.

You have to run calculations for each pixel, which is a lot of calculations. So I have a thread for each column of pixels. At the moment, I'm implementing Runnable. This improves the program's speed and doesn't have a noticeable effect on the overall processing speed on external processes (which is good).

For lighting, I'm going to take the point in 3D space where the camera's ray intersects the object and make sure that that point should be lit (accounting all light sources present, which has potential to be substantial enough to warrant multi-threading).

I would imagine that having threads create more threads (2D threading) is poor practice, but is there some library or method of implementing this that makes it efficient? I know that this would NOT lead to an infinite recursion, but I also don't want to overload my CPU. Essentially how do I handle a process that requires "2D threading" safely?

Upvotes: 1

Views: 93

Answers (2)

cmza
cmza

Reputation: 11

If you're doing a column per thread, you're losing one of the advantages of tiling -- ray coherence. Although, to be honest, I've never found it to be particularly advantageous but then again, I don't work on Arnold or Mental Ray...I'd try starting with a single ray and getting your quality and pps up as high as possible, and then farming out squares of your image to different threads...

Upvotes: 1

CodeBlind
CodeBlind

Reputation: 4569

You could just use an ExecutorService to manage your threads. Maybe try using Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()).

Your Runnable implementation could create more Runnable instances and submit them to the same ExecutorService. If you're sure that it won't create an infinite recursion, it should run to completion and not use any more threads than your hardware has available. The only thing you'd need to be careful about is that you don't create so many Runnable instances that you run out of memory. You'd also need to keep track of when all Runnable instances are complete, but the service provides mechanisms for doing just that (see Future in the Java API).

Upvotes: 2

Related Questions