Hi,
I’m trying to use SDL_Atomic, but I don’t understand it fully. My code seems to work in different variants I tried, but it also works if I use simple integer without atomic stuff, so I’m not sure it will guard against rare race conditions. Here’s what it needs to do:
I have a game where saving takes a lot of time (it uses JSON format and has 1000+ objects, so it’s slow) and I decided to use a secondary thread. I’m using a single bool flag to mark that world is “saving”, so that main code knows not to touch some important objects and it also shows to the user when it’s done.
MAIN THREAD runs this code:
bool isSaving = false;
while (true)
{
… poll and handle sdl events (some stuff that would modify world is ignored if isSaving)
… render stuff
}
SAVE THREAD runs this code:
void save()
{
isSaving = true;
… do stuff
isSaving = false;
}
The thread is detached and gets destroyed when this function is done.
How should I convert this code to use SDL_atomic functions?
It seems to me that using SDL_atomic_t instead of bool would be straightforward:
SDL_AtomicGet(SDL_atomic_t *a);
SDL_AtomicSet(SDL_atomic_t *a, int v);
But, SDL_atomic.h says:
- IMPORTANT:
- If you are not an expert in concurrent lockless programming, you should
- only be using the atomic lock and reference counting functions in this
- file. In all other cases you should be protecting your data structures
- with full mutexes.*
- The list of “safe” functions to use are:
- SDL_AtomicLock()
- SDL_AtomicUnlock()
- SDL_AtomicIncRef()
- SDL_AtomicDecRef()
Can I still use SDL_AtomicGet/Set and is there something important to know?
Thanks.