开发者

IPC via mmap'ed file: should atomics and/or volatile be used?

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:

  1. Should I use开发者_如何转开发 volatile qualifier (volatile int Data)?
  2. Should I use atomic operations on the shared data (__sync_fetch_and_add(&(shared->Data), 1))?

For future reference: Volatile: Almost Useless for Multi-Threaded Programming.


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.


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜