Main loop for rendering and updating logic or spawn new threads

Hi!

I want to know if this approach is correct:

I have the main thread, as always, and currently it does all the work. I want to try and use the 2 cores my computer has (i always relied on one core only for simplicity) so I’m thinking to use the main loop for the calculations and other stuff not related to rendering graphics and spawn a new thread for this.

My Display class (JFrame) uses different states (JPanels) to change levels and menus, so my first idea is to make the state’s superclass extend Thread and every new state I create will spawn a new thread that would run concurrently with the main loop, since there can be only 1 state present, no more than 2 threads would be present at all times.

Do you think this is a good approach?

Another question: If I have two threads, one for each core, do I need to put a sleep in the second thread? I have a sleeping timer for the rendering (main loop) to adjusting the frames so this are constant, but do I need to put the logic thread to sleep even for 1 ms or not?

Unless you’re making some kind of super large AAA game, you should be fine with 1 thread.

There is just no way that your game needs more than 1 thread. Besides, rendering happens on the GPU, not CPU. Unless you’re going through all the pixels on the screen.

The only time you should be having a second thread, is if your game has a lot of stuff to load. Than you could add another thread to load stuff and nothing more. That would make user experience better, because they wouldn’t have to wait for stuff to load.

Using seperate Threats shure can give you a boost in performance.
BUT, dont digg into that unless you create some very complex and demanding game simulation (using physics for example).

The effort to get it working right and flawless might not be worth it, when just developing a small indy game.
Suggesting: Stick to a single Thread for logic and rendering.

Thanks for the replies.

Anyway, I’m just doing this to get a better understanding of threads and concurrency while learning how to develop games.

I’ll stick to one thread for now then.

Thanks.

I’m using Java2D to make the game. I know how to draw 2D with LWJGL basically. I have to understand it better for me to be comfortable to make a game.

I’m using BufferedImages with createCompatibleImage so I guess I should be fine… Maybe if I get stuck at some point with the performance i’d switch to OpenGL.