Hello, I have a class with 2 bools and inside the class I have a function that toggles the bool when the user presses a key. Like this:
1 2 3 4 5 6 7
class Settings
{
public:
bool Toggle1 = true;
bool Toggle2 = true;
void Loop(); // this is a thread that is created from main, it checks if user presses a key and then flips the bool like this: Toggle1 = !Toggle1
};
I know the bool changes because I print it out to in console to test from the Loop thread, but when I try to check bool value in another class, it always reads the initial value not the changed value. This is how I check it:
1 2 3 4
while (S.Toggle1 == true) //S is Settings class object
{
//execute code
}
I know this is a newbie mistake and probably a very simple thing, but I really cannot figure this out.
Are you sure you're not checking against a default constructed copy of your Setting instance?
Is S global? Or is S a member variable of the other class?
Each instantiation and full specialization of the std::atomic template defines an atomic type. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races) http://en.cppreference.com/w/cpp/atomic/atomic