【问题标题】:Allocating a atomic on shared memory在共享内存上分配原子
【发布时间】:2018-07-14 20:23:26
【问题描述】:

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

【问题讨论】:

  • 为什么投反对票?

标签: c++ linux atomic


【解决方案1】:

是的,你可以这样做。这是我从 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

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多