Let's say we have the following:
void SetValue( __int64 a_i64Value );
__int64 GetValue( void ) const;
void MyClass::SetValue( __int64 a_i64Value )
m_i64Value = a_i64Value;
__int64 MyClass::GetValue( void ) const
We also have two threads:
ThreadB, each setting the value of
m_i64Value to something different.
Let's assume that
ThreadA executes and
SetValue is called. It writes 32 bits of
ThreadB executes, it calls
SetValue which also writes 32 bits of
ThreadA resumes and continues writing the other 32 bits of
ThreadB also writes the other half of
m_i64Value contains garbage, invalid data.
Question 1: Is this scenario valid? Can it happen on a 32 bit machine?
Anyway, this can be solved using
But let's suppose there is a
ThreadC which needs to read that value, using the member function
GetValue. When returning from
GetValue, 32 bits of
m_i64Value get written to
EAX register and 32 bits to
Question 2: What if 32 bits get written to
ThreadB resumes and writes to
m_i64Value and after that,
ThreadC resumes and the other 32 bits (changed by
ThreadB) go to
EDX? Is this also a possibility on 32 bit machines? If yes, what is the best way to return such a value (__int64, in this example)?
I guess one of the solutions could be this one:
void GetValue( __int64 *a_pi64Value )
if ( NULL != a_pi64Value )
InterlockedExchange64( *a_pi64Value, m_i64Value );
Question 3: But what if we still want to actually return the value and not copy it to the memory pointed by
a_pi64Value? Can this be done somehow thread-safely and using the return instruction?
Thanks in advance!