【发布时间】:2018-01-15 09:54:35
【问题描述】:
我需要在重新启动后保留 uint64_t 标记。
为了实现这一点,我使用boost::interprocess::mapped_region 来内存映射我在同一进程中创建的文件:
bip::file_mapping file(filename.c_str(), bip::read_write);
auto region = std::make_unique<bip::mapped_region>(file, bip::read_write);
然后我将地址转换为我的uint64_t 类型
using Tag = uint64_t;
Tag& curr_ = *reinterpret_cast<Tag*>(region->get_address());
现在我可以发布增量标签,获得“下一个标签”,结果在重启后保持不变
Tag next = curr_++;
请注意,此文件写入和读取仅由该过程。它的目的纯粹是为了提供持久性。
问题:
我的Tag& curr_ 是非易失性的,并且对内存映射区域执行 I/O 是未定义行为吗?
正确地说,我的代码是否需要 volatile 关键字?
下面的完整工作示例:
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <sys/stat.h>
#include <fstream>
#include <cstdint>
#include <memory>
#include <iostream>
namespace bip = boost::interprocess;
using Tag = uint64_t;
Tag& map_tag(const std::string& filename,
std::unique_ptr<bip::mapped_region>& region)
{
struct stat buffer;
if (stat(filename.c_str(), &buffer) != 0)
{
std::filebuf fbuf;
fbuf.open(filename.c_str(), std::ios_base::in |
std::ios_base::out |
std::ios_base::trunc |
std::ios_base::binary);
Tag tag = 1;
fbuf.sputn((char*)&tag, sizeof(Tag));
}
bip::file_mapping file(filename.c_str(), bip::read_write);
// map the whole file with read-write permissions in this process
region = std::make_unique<bip::mapped_region>(file, bip::read_write);
return *reinterpret_cast<Tag*>(region->get_address());
}
class TagBroker
{
public:
TagBroker(const std::string& filename)
: curr_(map_tag(filename, region_))
{}
Tag next()
{
return curr_++;
}
private:
std::unique_ptr<bip::mapped_region> region_;
Tag& curr_;
};
int main()
{
TagBroker broker("/tmp/tags.bin");
Tag tag = broker.next();
std::cout << tag << '\n';
return 0;
}
输出:
在运行过程中,保持持久性。
$ ./a.out
1
$ ./a.out
2
$ ./a.out
3
$ ./a.out
4
我不知道这是否正确,因为我的进程是唯一一个读取/写入 Tag& curr_ 的进程,或者它只是偶然工作,实际上是未定义的行为。
【问题讨论】:
-
我认为只有在您的程序之外的其他内容正在写入该文件时才需要使用 volatile?
-
@AndyG 我也是这么认为的——但由于 I/O 调度程序将处理从/写入磁盘的实际读取,这是否被认为是另一个过程?我的理解不是,也不需要 volatile ,但我不是 100% 确定,因此这个问题
标签: c++ volatile memory-mapped-files boost-interprocess