用C++实现进程同步,进程间共享内存
// 一,读共享内存源代码
// //ShareMemory_Read.cpp : 定义控制台应用程序的入口点。
**重点内容**
#include "stdafx.h"
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include
#include "afxwin.h" //=========互斥量========================================== #include "stdafx.h" #include
#include
#include
char name[100] = "BeiJing-LingYun"; //=========互斥量========================================== using namespace cv; using namespace std; #define BUF_SIZE 5038849 int ImgSaveIndex=0; int main() { // 打开共享的文件对象 while (true) { //------------互斥量------------------------------------------------------------------- HANDLE mutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, name); if (mutex == NULL) { // printf("打开失败\n"); } else { int a=0; } //printf("等待......\n"); DWORD res = WaitForSingleObject(mutex, 20000); switch (res) { case WAIT_OBJECT_0: { printf("收到信号......\n"); //-------------图像处理----------------------------------------------------------------- HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS,NULL,"ShareMemory"); if (hMapFile) { LPVOID lpBase = MapViewOfFile(hMapFile,FILE_MAP_ALL_ACCESS,0,0,0); // 将共享内存数据拷贝出来 //char szBuffer[BUF_SIZE] = {0}; char *szBuffer= new char[BUF_SIZE]; strcpy(szBuffer,(char*)lpBase); ////----------------存储图像--------------------------------------- Mat MImg; MImg=cv::Mat(1944, 2592,CV_8UC1); memcpy(MImg.data,szBuffer,2592*1944); ImgSaveIndex++; char ch_sf[20]; itoa(ImgSaveIndex,ch_sf,10); string strSaveImageTempPath; string strSavePath="D:\\JD_ImageAcq\\"; strSaveImageTempPath=strSavePath+ch_sf; //存储校正图 string strCalibateImg=strSaveImageTempPath+"_校正.bmp"; imwrite(strCalibateImg,MImg); //存储矫正图 //----------------存储图像--------------------------------------- //printf("%s",szBuffer); // 解除文件映射 UnmapViewOfFile(lpBase); // 关闭内存映射文件对象句柄 CloseHandle(hMapFile); } else { // 打开共享内存句柄失败 printf("OpenMapping Error\n"); //Sleep(2000); } } //-------------图像处理----------------------------------------------------------------- break; case WAIT_TIMEOUT: printf("超时没有收到.....\n"); break; case WAIT_ABANDONED: printf("另一个进程意外终止...\n"); break; default : break; } //一旦不再需要,注意一定要用 CloseHandle 关闭互斥体句柄。如对象的所有句柄都已关闭,那么对象也会删除 CloseHandle(mutex); //------------互斥量------------------------------------------------------------------- } system("pause"); return 0; }
//二,创建共享内存源代码:
//---------------共享内存------------------------------------------------------------------------
// 定义共享数据
cvtColor(MCorrectedImg, MCorrectedImg, COLOR_BGR2GRAY); //转换成灰度图
int channels = MCorrectedImg.channels();
int nRows = MCorrectedImg.rows; //行
int nCols = MCorrectedImg.cols* channels; //列
pDlg->m_pShareDate = new char[nRows * nCols * channels];
bool bb=pDlg->MatToChar(MCorrectedImg,pDlg->m_pShareDate);
LPVOID lpBase;
HANDLE hMapFile;
if (bb==true)
{
// 创建共享文件句柄
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // 物理文件句柄
NULL, // 默认安全级别
PAGE_READWRITE, // 可读可写