用boost共享内存实现进程通信的例子

时间:2022-12-24 19:36:38

发送端

#include "DBProc1.h"
#include <string>
#include <thread>
#include <boost/thread/thread.hpp>
using namespace boost::interprocess;
PLUG_COMPONENT_AUTO_REG(DBProc1)//DO NOT EDIT THIS
struct 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<interprocess_mutex> 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 <string>
#include <thread>
#include <boost/thread/thread.hpp>
PLUG_COMPONENT_AUTO_REG(DBProc2)//DO NOT EDIT THIS
struct 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<interprocess_mutex> lock(m_镜像->mutex);
                MyStruct* mu = static_cast<MyStruct*>(addr);
                std::cout << mu->s << std::endl;
            }
            boost::this_thread::interruptible_wait(1000);//同理这个也需要放在外面
        }
        
    });
    getchar();
    return true;
}
//------------------------------------------------------------------------------------------------------------------