Using C++ std::atomic is a good way to prevent accessing a variable in the middle of its modification. There's a brief example here:
And since it's a standard C++ library feature, there's a lot written about it online. It's a little confusing at first, but very powerful.