Linux无锁共享内存,c – 共享内存IPC同步(无锁)

Boost Interprocess支持共享内存.

Boost Lockfree具有Single-Producer Single-Consumer队列类型(spsc_queue).这基本上就是你所说的循环缓冲区.

这是一个使用此队列以无锁方式传递IPC消息(在本例中为string类型)的演示.

定义类型

首先,让我们定义我们的类型:

namespace bip = boost::interprocess;

namespace shm

{

template

using alloc = bip::allocator;

using char_alloc = alloc;

using shared_string = bip::basic_string, char_alloc >;

using string_alloc = alloc;

using ring_buffer = boost::lockfree::spsc_queue<

shared_string,

boost::lockfree::capacity<200>

// alternatively, pass

// boost::lockfree::allocator

>;

}

为简单起见,我选择演示运行时大小的spsc_queue实现,随机请求200个元素的容量.

shared_string typedef定义了一个从共享内存段透明分配的字符串,因此它们也与另一个进程“神奇地”共享.

消费者方面

这是最简单的,所以:

int main()

{

// create segment and corresponding allocator

bip::managed_shared_memory segment(bip::open_or_create, "MySharedMemory", 65536);

shm::string_alloc char_alloc(segment.get_segment_manager());

shm::ring_buffer *queue = segment.find_or_construct<:ring_buffer>("queue")();

这将打开共享内存区域,找到共享队列(如果存在).注意这应该在现实生活中同步.

现在进行实际演示:

while (true)

{

std::this_thread::sleep_for(std::chrono::milliseconds(10));

shm::shared_string v(char_alloc);

if (queue->pop(v))

std::cout << "Processed: '" << v << "'

";

}

消费者只是无限地监视队列中的待处理作业,并且每个处理一个~10ms.

制片人方面

生产者方面非常相似:

int main()

{

bip::managed_shared_memory segment(bip::open_or_create, "MySharedMemory", 65536);

shm::char_alloc char_alloc(segment.get_segment_manager());

shm::ring_buffer *queue = segment.find_or_construct<:ring_buffer>("queue")();

再次,在初始化阶段添加适当的同步.此外,您可能会让生产者负责在适当的时候释放共享内存段.在这个演示中,我只是“让它挂起”.这很适合测试,见下文.

那么,制作人做了什么?

for (const char* s : { "hello world", "the answer is 42", "where is your towel" })

{

std::this_thread::sleep_for(std::chrono::milliseconds(250));

queue->push({s, char_alloc});

}

}

是的,生产者在~750ms内准确生成3条消息,然后退出.

请注意,如果我们这样做(假设一个带有作业控制的POSIX shell):

./producer& ./producer& ./producer&

wait

./consumer&

将“立即”打印3×3消息,同时让消费者继续运行.干

./producer& ./producer& ./producer&

在此之后,将再次显示“涓涓细流”的消息(以3~24毫秒的间隔突发),因为消费者仍然在后台运行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值