M
mlimber
I am using placement new to locate a shared data structure at a
particular location in shared memory. The problem is that when I access
the data on one of the two processors sharing it, I don't get the same
values seen by the other processor (which uses a cache-less access
method, unlike what follows). Here's a reduced example:
struct SharedData
{
enum Item { A=0, B=1 };
// Note volatile:
int Get( Item i ) const volatile { return data_[ i ]; }
// ...
private:
int data_[ 2 ];
};
void Foo()
{
void *const addr = reinterpret_cast<void*>( 0x8000 );
volatile SharedData *const data = new( addr ) SharedData;
const int a1 = data->Get( SharedData::A );
const int a2 = data->Get( SharedData::A );
// ...
}
The problem is that a1 and a2 may not be the same because the second
processor may modify the value - a classic case for the volatile
qualifier. The C way to handle this would be something like:
volatile int* const a = reinterpret_cast<volatile int*>( 0x8000 );
volatile int* const b = reinterpret_cast<volatile int*>( 0x8004 );
I thought, however, that applying volatile to the pointer-type in Foo()
and the appropriate member functions in SharedData would do basically
the same thing - namely, force all the data members of SharedData to be
volatile. Am I mistaken?
Cheers! --M
particular location in shared memory. The problem is that when I access
the data on one of the two processors sharing it, I don't get the same
values seen by the other processor (which uses a cache-less access
method, unlike what follows). Here's a reduced example:
struct SharedData
{
enum Item { A=0, B=1 };
// Note volatile:
int Get( Item i ) const volatile { return data_[ i ]; }
// ...
private:
int data_[ 2 ];
};
void Foo()
{
void *const addr = reinterpret_cast<void*>( 0x8000 );
volatile SharedData *const data = new( addr ) SharedData;
const int a1 = data->Get( SharedData::A );
const int a2 = data->Get( SharedData::A );
// ...
}
The problem is that a1 and a2 may not be the same because the second
processor may modify the value - a classic case for the volatile
qualifier. The C way to handle this would be something like:
volatile int* const a = reinterpret_cast<volatile int*>( 0x8000 );
volatile int* const b = reinterpret_cast<volatile int*>( 0x8004 );
I thought, however, that applying volatile to the pointer-type in Foo()
and the appropriate member functions in SharedData would do basically
the same thing - namely, force all the data members of SharedData to be
volatile. Am I mistaken?
Cheers! --M