我自己写了一个类,就是创建一个共享内存,然后实现进程之间共享数据,比如A进程就是往内存里写入数据,B进程就是从内存里读取数据,当然这是需要加锁互斥的,我自己也写了一个锁,但是锁偶尔会出问题:
例如:A进程依次往内存里写入ABCDEFG,正常情况B读出也是ABCDEFG, 但是却会出现ABCCEFG这样的情况,请各位大侠指教一下
上代码
C/C++ code m_lpFileMapBuffer = MapViewOfFile(m_hFileMap, dwAccess, 0, 0, dwSize);LPVOID ShareMemory::GetBuffer(){ return (m_lpFileMapBuffer)?(m_lpFileMapBuffer):(NULL);}void ShareMemory::Lock(){ while ( InterlockedExchange(&m_lock, RESOURCE_IN_USE) == RESOURCE_IN_USE ) Sleep(1);}void ShareMemory::Unlock(){ InterlockedExchange(&m_lock, RESOURCE_IN_FREE);}BOOL ShareMemory::WriteData(char
*pData, DWORD dwSize){ Lock(); BOOL ret = FALSE; char
*p = (char
*)GetBuffer(); if (p) { memcpy(p, (char*)&pData, dwSize); ret = TRUE; } Unlock(); return ret;}BOOL ShareMemory::ReadData(char*
&pData, DWORD dwSize){ Lock(); BOOL ret = FALSE; char
*p = (char
*)GetBuffer(); if (p) { p = pData; ret = TRUE; } Unlock(); return ret;} |