Hello guys, I reached the point where I care about the sync between threads because I encountered a big problem long time ago but now it turned to be really annoying. My project has 4 thread which 1 of them doesn't need sync (audio one). The other threads are: Scripting (LUA), Physics (Bullet 2.83.7) and Rendering thread. I tried to add some ghetto bools to test if they sync better, it works but I don't want to do this since it's not good and also it doesn't work properly when the physics thread has a lot of entities to process. You can see the main problem here. As you can see when there are no entities the character goes decently smooth but when there are tons of entities it's so lagged and annoying. There are examples for multithreading in Bullet but I don't know if that's enough to cover my problem since scripting thread also change entities position, velocity etc. I tried using the following simple code to sync threads but I think it's not enough nor good practice of mutex concept.
class CBarrier
{
public:
CBarrier(const CBarrier&) = delete;
CBarrier& operator=(const CBarrier&) = delete;
explicit CBarrier() : m_continue(true), m_gen(0) {}
void wait_continue()
{
unsigned int gen = m_gen.load();
m_continue = false;
while (m_gen == gen && !m_continue)
{
std::this_thread::yield();
}
}
void set_continue()
{
unsigned int gen = m_gen.load();
if (m_gen.compare_exchange_weak(gen, gen + 1))
{
m_continue = true;
}
}
private:
std::atomic<bool> m_continue;
std::atomic<unsigned int> m_gen;
};
This class has a very simple use so you can guess how it works. I heard rendering thread should wait until physics thread is done (like Unity does). I need some tips about how to sync everything properly, like what I should use, winapi critical sections, mutexes, atomic, a mix of some of them...? I'm a bit confused now. Someone maybe knows about this and he/she can recommend me what I should use to achieve my goal. Maybe some kind of organization for threads, the correct flow of the game etc. Thanks for reading :)
Edit: I've been reading about bullet physics timestep and fixed timestep, maybe could it be the problem? Also entities that are processed from the physics thread directly without changing anything from them (only gravity and collisions) are smooth but since I move my character from the scripting thread the problem appears. Should I really wait scripting thread before rendering...?