Reputation: 229
I want to know what is a good practice in using objects stored in shared memory. The options I have in my mind are:
Let me explain the problem that I have:
I have two processes running on Linux on FPGA. They communicates data via the shared memory. Since they lock each other by binary semaphore, only one process do its job at a time. Compiler is g++ 3.4.x. My current code is something like below:
struct MyTime
{
int32 dayNumber;
int32 milliSecOfDay;
void convert(double* answer);
};
struct MyData
{
double var1;
MyTime time;
};
volatile MyData* ptr;
ptr = (volatile MyData*)shmat(shmid, NULL, 0);
double answer;
ptr->time.convert(&answer); //< ERROR(*)
*: error: passing const volatile TimeTTJ2000' as
this' argument of `bool TimeTTJ2000::get_Tu_UT1(double&, const int32&, const int32&) const' discards qualifiers
(The above code is just made up for explanation. The error message is from my real code, in which the size of MyData is much larger.)
To remove that error, it seems to me that I would have to define another member function like
MyTime::convert(double* answer) volatile;
But it seems to me ridiculous that I have to add 'volatile' to all the functions in the libraries that are not necessarily mine.
To avoid having 'volatile' everywhere, I think I can copy the entire data in shared memory to local right after one process is unlocked, and write back to shared memory right before the process is locked. By this way, I am not bothered with volatile, but still is this wise thing to do?
Or can I access shared memory data without using volatile in first place? That would make my life easier. (I have little experience in shared memory and volatile. I'm not very certain when volatile is needed. Of course I know basics like, volatile suppresses optimization.)
Upvotes: 3
Views: 1495
Reputation: 64223
But it seems to me ridiculous that I have to add 'volatile' to all the functions in the libraries that are not necessarily mine.
That is what the c++ standard says it should be done. You can cast away the const/volatile specifier, but by doing that, you may introduce UB.
Or can I access shared memory data without using volatile in first place?
Yes, you do not need volatile to access shared memory. And since you are locking the access with a semaphore, you do not need to copy data.
You would need volatile in a case your FPGA writes to some memory (which is not shared memory).
Upvotes: 1