【问题标题】:Using a memory mapped file for persistence - is volatile required?使用内存映射文件进行持久性 - 需要 volatile 吗?
【发布时间】: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&amp; 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&amp; curr_ 的进程,或者它只是偶然工作,实际上是未定义的行为。

【问题讨论】:

  • 我认为只有在您的程序之外的其他内容正在写入该文件时才需要使用 volatile?
  • @AndyG 我也是这么认为的——但由于 I/O 调度程序将处理从/写入磁盘的实际读取,这是否被认为是另一个过程?我的理解不是,也不需要 volatile ,但我不是 100% 确定,因此这个问题

标签: c++ volatile memory-mapped-files boost-interprocess


【解决方案1】:

在这种情况下,没有。

在底层,Boost 的 interprocess/mapped_region.hpp 正在使用mmap,它将返回一个指向内存映射区域的指针。

如果您怀疑另一个进程(或硬件)可能正在写入您的文件,您只需要使用volatile

(这将是您应该提供的最基本的同步,因为volatile 强制在每次访问时从内存中读取。如果您可以控制进程,您可以尝试更高级的同步,例如信号量。)

【讨论】:

  • 所以对于这个特殊的用例,我的过程是只有一个写入文件,然后volatile 不是必需的,也不需要更高级同步,比如信号量等?
  • 是的,先生
猜你喜欢
  • 2020-11-09
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2020-06-22
  • 2019-06-09
  • 2020-11-05
相关资源
最近更新 更多