Initial Commit

master
Kirigaya Kazuto 2017-11-16 21:47:54 +08:00
commit 3323a8bdb5
2 changed files with 126 additions and 0 deletions

88
WinUtil.cpp Normal file
View File

@ -0,0 +1,88 @@
#include "WinUtil.h"
using namespace std;
SharedMemory::SharedMemory(const string& name)
{
hMap=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,name.c_str());
if(hMap!=NULL) pMem=MapViewOfFile(hMap,FILE_MAP_ALL_ACCESS,0,0,0);
else pMem=nullptr;
}
SharedMemory::SharedMemory(const string& name,int size)
{
hMap=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,size,name.c_str());
if(hMap!=NULL) pMem=MapViewOfFile(hMap,FILE_MAP_ALL_ACCESS,0,0,0);
else pMem=nullptr;
}
SharedMemory::~SharedMemory()
{
if(pMem)
{
UnmapViewOfFile(pMem);
}
if(hMap!=NULL)
{
CloseHandle(hMap);
}
}
bool SharedMemory::isReady() const
{
return (hMap!=NULL);
}
void* SharedMemory::get()
{
return pMem;
}
NamedMutex::NamedMutex(const string& name, bool create)
{
if(create)
{
hmtx=CreateMutex(NULL,TRUE,name.c_str());
}
else
{
hmtx=OpenMutex(MUTEX_ALL_ACCESS,FALSE,name.c_str());
}
if(hmtx==NULL)
{
errcode=GetLastError();
}
}
NamedMutex::~NamedMutex()
{
if(hmtx!=NULL)
{
CloseHandle(hmtx);
}
}
bool NamedMutex::isReady() const
{
return (hmtx!=NULL);
}
DWORD NamedMutex::getError() const
{
return errcode;
}
void NamedMutex::wait()
{
WaitForSingleObject(hmtx,INFINITE);
}
void NamedMutex::wait_for(int ms)
{
WaitForSingleObject(hmtx,ms);
}
void NamedMutex::release()
{
ReleaseMutex(hmtx);
}

38
WinUtil.h Normal file
View File

@ -0,0 +1,38 @@
#include <string>
#include <windows.h>
class SharedMemory
{
public:
/// Open a shared memory
SharedMemory(const std::string& name);
/// Create a shared memory
SharedMemory(const std::string& name,int size);
/// auto close, destroy memory.
~SharedMemory();
bool isReady() const;
void* get();
private:
HANDLE hMap;
void* pMem;
};
class NamedMutex
{
public:
NamedMutex(const std::string& name,bool create=false);
~NamedMutex();
bool isReady() const;
DWORD getError() const;
/// If the mutex has been occupied by this process, wait() will return immediately.
void wait();
void wait_for(int ms);
void release();
private:
HANDLE hmtx;
DWORD errcode;
};