0
我需要在不同進程間交換一些變量,並通過共享內存嘗試此操作。以下代碼是此嘗試的簡化版本。該計劃按預期工作,但我想確保交流不僅因運氣而起作用。同步mmaped區域訪問的正確方法是什麼
我的主要問題是,是否足以將所有指針聲明爲volatile,以確保編譯器無法優化內存讀取?或者我需要插入一些額外的同步命令?
#include <sys/mman.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <type_traits>
struct Exchange
{
int x;
};
int main()
{
int fd = open("/dev/shm/foobar", O_RDWR | O_CREAT, 0600);
if(fd == -1)
{
std::cerr << "Open failed\n";
return 1;
}
if(ftruncate(fd, sizeof(Exchange)))
{
close(fd);
std::cerr << "Resize failed\n";
return 1;
}
auto xch = static_cast<volatile Exchange*>(
mmap(0, sizeof(Exchange),
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0));
if(!xch)
{
std::cerr << "no mapping\n";
return 1;
}
xch->x=23;
while(1)
{
// Do I need to insert some sync instruction here?
std::cout << xch->x << std::endl;
xch->x++;
msync((void*)(xch), sizeof(*xch), MS_SYNC);
sleep(1);
}
}