Qt QSharedMemory共享内存

1.简介

QSharedMemory提供多个线程和进程对共享内存段的访问。它还为单个线程或进程提供了一种锁定内存以进行独占访问的方法。

记住,在读取或写入共享内存之前,使用lock()锁定共享内存,并记住在完成之后使用unlock()释放锁。

当QSharedMemory的最后一个实例与共享内存段分离时,QSharedMemory会自动销毁共享内存段,并且不会保留对该段的引用。

2.常用方法

void setKey(const QString &key) 设置与平台无关key值。如果key与当前key相同,则函数不做任何操作就返回。
bool create(int size, AccessMode mode = ReadWrite) 创建一个共享内存段,并将key传递给构造函数,
bool attach(AccessMode mode = ReadWrite) 将进程附加到key标识的共享内存段
bool detach() 将进程与共享内存段分离。
bool lock() 锁定共享内存段,供该进程访问
bool unlock() 释放共享内存段上的锁

3.示例

这里写了两个进程,一个读,一个写。 

Qt QSharedMemory共享内存_第1张图片

写进程源码:

#include "WSharedMemory.h"
#include "ui_WSharedMemory.h"
#include 

WSharedMemory::WSharedMemory(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WSharedMemory)
{
    ui->setupUi(this);

    m_sharedMemory = new QSharedMemory(this);
}

WSharedMemory::~WSharedMemory()
{
    delete ui;
}

void WSharedMemory::on_btnWrite_clicked()
{
    //设置key
    m_sharedMemory->setKey("key");

    if(m_sharedMemory->isAttached())
    {
        m_sharedMemory->detach();
    }

    //创建共享内存端 大小100
    if(!m_sharedMemory->create(100, QSharedMemory::ReadWrite))
    {
        qDebug() << "创建共享内存失败: " << m_sharedMemory->errorString();
        return;
    }

    //写的时候先lock
    m_sharedMemory->lock();

    char* str = (char *)m_sharedMemory->data();

    QByteArray byte = ui->textEdit->toPlainText().toUtf8();

    //写入数据
    memcpy(str, byte.data(),byte.size());

    //写完后解锁
    m_sharedMemory->unlock();

}

读进程源码:

#include "WSharedMemory.h"
#include "ui_WSharedMemory.h"
#include 

WSharedMemory::WSharedMemory(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WSharedMemory)
{
    ui->setupUi(this);

    m_sharedMemory = new QSharedMemory(this);
}

WSharedMemory::~WSharedMemory()
{
    delete ui;
}

void WSharedMemory::on_btnRead_clicked()
{
    //设置访问标识
    m_sharedMemory->setKey("key");

    if(!m_sharedMemory->attach())
    {
        qDebug() << "attach error";
    }

    //读数据前先lock
    m_sharedMemory->lock();

    char* str = (char *)m_sharedMemory->data();

    char* out = new char[m_sharedMemory->size()];

    //读取数据到out中
    memcpy(out, str, m_sharedMemory->size());

    //显示到界面上
    ui->textEdit->append(QString(out));

    //读取完后unlock
    m_sharedMemory->unlock();

    //将进程与共享内存段分离
    m_sharedMemory->detach();
}

你可能感兴趣的:(Qt入门,qt,开发语言,QSharedMemory,共享内存)