c++ - 在共享内存上分配原子

标签 c++ linux atomic

我正在尝试在共享内存块上分配原子(在Linux上)。 原子将同时被多个线程访问和修改。 将其分配在共享内存上的原因是因为我想保留这些值,因此如果我的进程重新启动,则可以恢复之前的状态。 我知道,如果我在共享内存中使用互斥体,我必须将其初始化为共享内存。对于原子有这样的要求吗? 这可行吗?

最佳答案

是的,你可以做到。这是我从 Quora ( ripped code from Quora ) 中摘取的示例,不是我的代码,并且包含 boost,所以我没有测试它:

#include <atomic>
#include <string>
#include <iostream>
#include <cstdlib>
#include <boost/interprocess/managed_shared_memory.hpp>

using namespace std::string_literals;
namespace bip = boost::interprocess;
static_assert(ATOMIC_INT_LOCK_FREE == 2,
              "atomic_int must be lock-free");
int main(int argc, char *argv[])
{
  if(argc == 1) //Parent process
  {
    struct shm_remove {
      shm_remove() { bip::shared_memory_object::remove("szMem");}
      ~shm_remove(){ bip::shared_memory_object::remove("szMem");}
    } remover;
    bip::managed_shared_memory segment(bip::create_only,
                                       "szMem", 65536);
    auto ap = segment.construct<std::atomic_int>("the counter")(0);
    //Launch 5 child processes
    std::string s = argv[0] +" child"s;
    std::system((s + '&' + s + '&' + s + '&' + s + '&' + s).c_str());
    std::cout << "parent existing: counter = " << *ap << '\n';
    segment.destroy<std::atomic_int>("the counter");
 } else { // child
    bip::managed_shared_memory segment(bip::open_only, "szMem");
    auto res = segment.find<std::atomic_int>("the counter");
    for(int n = 0; n < 100000; ++n)
        ++*res.first; // C++17 will remove the dumb "first"
    std::cout << "child exiting, counter = " << *res.first << '\n';
  }
}

这里是文档: link to Boost docs

关于c++ - 在共享内存上分配原子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614784/

相关文章:

c++ - 静态 QApplication 变量使 Mac 在退出时报告崩溃

linux - 设备树中的 Gpio hog 是什么?

Linux:减号 -* 在 bash 脚本中意味着什么

linux - FFMPEG rtsp流向输出文件添加时间戳

c - ARM 代码中的读-修改-写操作应该使用什么抽象

c++ - "pseudo-atomic"C++ 操作

java - 对 volatile 和 Atomic 类有一些疑问?

C++/Tk如何执行一般的tcl代码?

c++ - undefined reference 错误 : `ClassName::ClassMember`

c++ - 新套接字的名称