I use a mmap'ed file to share data between processes.
The code is like this:
struct Shared
{
int Data;
};
int file = open("file.dat", O_RDWR);
Shared* shared = static_cast<Shared*>(
mmap(0, sizeof(Shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, file, 0));
shared->Data++;
The questions are:
volatile int Data
)? __sync_fetch_and_add(&(shared->Data), 1)
)? For future reference: Volatile: Almost Useless for Multi-Threaded Programming .
There is no guarantee that volatile
will work correctly across multiple processors, the thing you need to check is whether that intrinsic inserts the appropriate memory barriers during the operation.
Is this some sort of semaphore? if so, you are better off using the platform implementation of such a construct.
You should not use volatile when changing an integer from more than one thread. Volatile is both not necessary and not sufficient. Atomic operations will do.
No need for both volatile and atomic accesses. IPC using mmap works fine without them.
If you need to inform whether something changed, you can use message queues , but you can also use them instead of mmap (depends how big is the message you want to send. mmap works good is the data is big, but MQ is it is smaller then 200k)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.