博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用boost共享内存实现进程通信的例子
阅读量:6787 次
发布时间:2019-06-26

本文共 2689 字,大约阅读时间需要 8 分钟。

发送端

#include "DBProc1.h"#include 
#include
#include
using namespace boost::interprocess;PLUG_COMPONENT_AUTO_REG(DBProc1)//DO NOT EDIT THISstruct MyStruct{ int a; int b; std::string s; int v[3];};//------------------------------------------------------------------------------------------------------------------DBProc1::DBProc1(){}DBProc1::~DBProc1(){}bool DBProc1::test(){ shared_memory_object mu(open_or_create, "mutex", read_write); mu.truncate(sizeof(镜像)); mapped_region mru(mu, read_write); void* addrmu = mru.get_address(); m_镜像 = new(addrmu)镜像; shared_memory_object smo(open_or_create, "gongxiang", read_write); smo.truncate(10 * 1024); mapped_region mr(smo, read_write); void* addr = mr.get_address(); MyStruct* my = new(addr)(MyStruct); int i = 100; std::thread th([&]() { while (true) { { scoped_lock
lock(m_镜像->mutex); my->a = 1; my->b = 2; char buf[20]; itoa(i++, buf, 10); my->s = buf; my->v[0] = 90; my->v[1] = 80; my->v[2] = 70; } boost::this_thread::interruptible_wait(1000);//这个需要放在外面,放在里面虽然当前放弃了时间片,但当前进程还是拥有锁,别的进程还是不能执行,所以需要放在外面 } }); getchar(); return true;}//------------------------------------------------------------------------------------------------------------------

接收端

#include "DBProc2.h"#include 
#include
#include
PLUG_COMPONENT_AUTO_REG(DBProc2)//DO NOT EDIT THISstruct MyStruct{ int a; int b; std::string s; int v[3];};//------------------------------------------------------------------------------------------------------------------DBProc2::DBProc2(){}DBProc2::~DBProc2(){}bool DBProc2::test(){ shared_memory_object shm(open_only ,"mutex" ,read_write); mapped_region mu(shm ,read_write); void * addrmu = mu.get_address(); m_镜像 = static_cast
<镜像*>
(addrmu); shared_memory_object sho(open_only ,"gongxiang" ,read_write); mapped_region mr(sho ,read_write); void * addr = mr.get_address(); std::thread th([=]() { while (1) { { scoped_lock
lock(m_镜像->mutex); MyStruct* mu = static_cast
(addr); std::cout << mu->s << std::endl; } boost::this_thread::interruptible_wait(1000);//同理这个也需要放在外面 } }); getchar(); return true;}//------------------------------------------------------------------------------------------------------------------

 

转载地址:http://cgigo.baihongyu.com/

你可能感兴趣的文章
乱码问题总结
查看>>
C++学习前理论
查看>>
HDU 2586 How far away ?
查看>>
HTTP协议中POST、GET、HEAD、PUT等请求方法 (自己学习)
查看>>
c++11: bind用法
查看>>
讨论:C#Gridview增加超链接列
查看>>
Service
查看>>
canvas 画板
查看>>
TYVJ P1045 &&洛谷 1388 最大的算式 Label:dp
查看>>
10+31=100小组项目第五周总结报告
查看>>
Python 爬取高清桌面壁纸
查看>>
测试-html格式
查看>>
选择排序
查看>>
安装nginx&&node环境nginx转发端口
查看>>
Java知多少(7)类与对象
查看>>
评论递归无极显示
查看>>
用学习逃避成长,听新知缓解焦虑
查看>>
selenium 如何处理table
查看>>
从流程浅析网站性能优化点
查看>>
Web前端面试宝典(最新)
查看>>