I'm creating a simple 2D game engine and I want to update and render the sprites in different threads, to learn how it is done.
I need to synchronise the update thread and the render one. Currently, I use two atomic flags. The workflow looks something like:
Thread 1 -------------------------- Thread 2
Update obj ------------------------ wait for swap
Create queue ---------------------- render the queue
Wait for render ------------------- notify render done
Swap render queues ---------------- notify swap done
In this setup I limit the render thread's FPS to the update thread's FPS.
Besides I use sleep()
to limit both render and update thread's FPS to 60, so the two wait functions won't wait much time.
The problem is:
The average CPU usage is around 0.1%. Sometimes it's go up to 25% (in a quad core PC). It means that a thread is waiting for the other because the wait function is a while loop with a test and set function, and a while loop will use all your CPU resources.
My first question is: is there another way to synchronise the two threads?
I noticed that std::mutex::lock
don't use the CPU while it is waiting to lock a resource so it isn't a while loop. How does it work?
I can't use std::mutex
because I will need to lock them in one thread and unlock in another thread.
The other question is; since the program runs always at 60 FPS why does sometimes its CPU usage jumps to 25%, meaning that one of the two wait is waiting a lot? (the two threads are both limited to 60fps so they ideally won't need a lot of synchronisation).
Edit: Thanks for all the replies. First I want to say I don't start a new thread each frame for render. I start both update and render loop at the beginning. I think multithreading can save some time : I have the following functions: FastAlg() and Alg(). Alg() is both my Update obj and render obj and Fastalg() is my "send render queue to" renderer" ". In a single thread :
Alg() //update
FastAgl()
Alg() //render
In two thread:
Alg() //update while Alg() //render last frame
FastAlg()
So maybe multithreading can save same time. (actually in a simple math application it does, where alg is a long algorithm amd fastalg a faster one)
I know that sleep isn't a good idea, although I ve never have problems. Will this will better?
While(true)
{
If(timer.gettimefromlastcall() >= 1/fps)
Do_update()
}
But this will be a infinite while loop that will use all the CPU. Can I use sleep(a number < 15) to limit the usage? In this way it will run at, for example, 100 fps, and the update function will be called just 60 times per second.
To synchronise the two threads I will use waitforsingleobject with createSemaphore so I will able to lock and unlock in different thread (whitout using a while loop), won't I?