1.简介
QSharedMemory提供多个线程和进程对共享内存段的访问。它还为单个线程或进程提供了一种锁定内存以进行独占访问的方法。
记住,在读取或写入共享内存之前,使用lock()锁定共享内存,并记住在完成之后使用unlock()释放锁。
当QSharedMemory的最后一个实例与共享内存段分离时,QSharedMemory会自动销毁共享内存段,并且不会保留对该段的引用。
2.常用方法
3.示例
这里写了两个进程,一个读,一个写。
写进程源码:
#include "WSharedMemory.h"
#include "ui_WSharedMemory.h"
#include <QDebug>
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 <QDebug>
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();
}