通过 mmap 编辑的文件进行 IPC:应该使用原子和/或易失性吗?
我使用 mmap 文件在进程之间共享数据。
代码是这样的:
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++;
问题是:
- 我应该使用 volatile 限定符(
volatile int Data
)吗? - 我应该对共享数据使用原子操作 (
__sync_fetch_and_add(&(shared->Data), 1)
) 吗?
供将来参考:易失性:对于多线程编程几乎没用。
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:
- Should I use volatile qualifier (
volatile int Data
)? - 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从多个线程更改整数时,不应使用 volatile。挥发性既不是必要的,也不是充分的。原子操作就可以了。
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.
不需要易失性和原子访问。没有它们,使用 mmap 的 IPC 也能正常工作。
如果您需要通知某些内容是否发生更改,可以使用消息队列,但您也可以使用它们而不是 mmap(取决于您要发送的消息有多大。当数据很大时,mmap 效果很好,但 MQ 小于 200k)
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)