在共享内存上分配原子
Allocating a atomic on shared memory
我正在尝试在共享内存块上分配原子(在Linux上(。原子将同时访问和修改我的多个线程。在共享内存上分配的背后理性是因为我想坚持这些值,因此,如果我的过程重新启动,则可以恢复先前的状态。我知道一个事实,如果我在共享内存中使用互斥品,则必须将其作为共享初始化。对原子有什么要求吗?这是可行的吗?
是的,您可以做到。这是我从Quora(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';
}
}
这是文档:链接到Boost Docs
相关文章:
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- 是否可以在专用内存空间中分配一个为提升管理共享内存而创建的对象
- 如何进行放置分配特征::矩阵到共享内存(或堆)?
- 使用运算符 = 重新分配共享指针会导致内存泄漏
- 对共享指针重新分配进行切片
- 使用 MapViewOfFile 分配静态共享内存
- 提升进程间:在循环中分配共享内存
- 呼叫获取后,将共享_ptr分配给另一个
- 如何将结构分配给共享内存i C
- 在共享内存上分配原子
- 使用 boost::interprocess 在共享内存中分配用户定义的结构
- 查询与将地址分配给共享_ptr有关
- 如果我使用共享内存,可以分配多少个块
- 如何使用boost :: intercons :: vector在共享内存中分配复杂的结构
- 如何在共享内存中分配 CGAL 的半边结构?
- 动态分配的 int 数组的共享指针触发了断点
- 为什么共享指针分配会"交换"?
- 2D 阵列的 CUDA 动态共享内存分配
- C++ 通过共享指针将值分配给结构成员会导致 SIGSEGV
- 共享指针在未分配的情况下工作