I am looking for some clarity on the necessity to lock a variable if std::atomic<> is used on it. Please consider the following code:
std::atomic<int> my_integer;
void Thread1()
{
if (condition1)
{
my_integer = 5;
}
if (my_integer == 7)
{
doSomething();
}
}
void Thread2()
{
if (condition2)
{
my_integer = 7;
}
}
Is there any reason to use a mutex around the writes and reads to my_integer? Or would the atomic variable provide adequate thread safe protection? Is there a possibility of any race condition occurring here? If so, what would that race condition be? Thanks in advance for any insight!
I was thinking that std::atomic should protect the assignment to my_integer, so that whenever it is read, it is always the most up-to-date version of the variable.