#include "stdafx.h"
#include "stdio.h"
#include "afxmt.h"
int i=50;
HANDLE hMutex1;
//CCriticalSection Cmysection;
HANDLE g_hMutexShrMem; // Used for hare memory write&read
bool WriteSharedMemory(char* pName,void *pData, UINT nSize)
{
if(g_hMutexShrMem == NULL){
g_hMutexShrMem = CreateMutex(NULL, FALSE, "ShrMem");
}
WaitForSingleObject(g_hMutexShrMem, INFINITE);
HANDLE hFileMapping = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nSize, pName );
if ( hFileMapping == NULL ) {
ReleaseMutex(g_hMutexShrMem);
return false;
}
void *pMapView = MapViewOfFile( hFileMapping, FILE_MAP_WRITE, 0, 0, nSize );
if ( pMapView == NULL ) {
ReleaseMutex( g_hMutexShrMem );
return false;
}
//Clear share memory
memset( pMapView, 0, nSize );
//write to memory
memcpy( pMapView, pData, nSize );
UnmapViewOfFile( pMapView );
ReleaseMutex( g_hMutexShrMem );
return true;
}
bool ReadSharedMemory( char* pName, void *pData, UINT nSize )
{
if(g_hMutexShrMem == NULL){
g_hMutexShrMem = CreateMutex(NULL, FALSE, "ShrMem");
}
WaitForSingleObject( g_hMutexShrMem, INFINITE );
HANDLE hFileMapping = OpenFileMapping( FILE_MAP_ALL_ACCESS, FALSE, pName );
if ( hFileMapping == NULL )
{
ReleaseMutex( g_hMutexShrMem );
return false;
}
void *pMapView = MapViewOfFile( hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, nSize );
if ( pMapView == NULL )
{
ReleaseMutex( g_hMutexShrMem );
return false;
}
// Read from share memory
memcpy( pData, pMapView, nSize );
// 共有メモリの内容をクリアする
memset( pMapView, 0, nSize );
UnmapViewOfFile( pMapView );
ReleaseMutex( g_hMutexShrMem );
return true;
}
DWORD WINAPI clientthread(LPVOID lpparam)
{
// while(true){
::WaitForSingleObject(hMutex1,INFINITE);
// if(i>0){
// ::Sleep(100);
// printf("thread %d is runing ",num);
// printf("%d/n",i);
// i=i-1;}
// else{
// break;
// }
int *p;
int m;
p = &m;
*p=10;
char a[10]="rongning";
// a[0]='r';
// a[1]='o';
// a[2]='4';
char* tt;
tt=a;
WriteSharedMemory("NM3200",tt,10);
::ReleaseMutex(hMutex1);
// }
return 0;
}
DWORD WINAPI clientthread2(LPVOID lpparam)
{
// int num=(int)lpparam;
// while(true){
//
::WaitForSingleObject(hMutex1,INFINITE);
// if(i>0){
//
// ::Sleep(100);
// printf("thread %d is runing ",num);
// printf("%d/n",i);
// i=i-1;
// }
// else{
// break;
// }
char ct[12];
ReadSharedMemory("NM3200",ct,12);
printf(ct);
// for(int i=0;i<10;i++){
// printf("%c",ct[i]);
// }
::ReleaseMutex(hMutex1);
// }
return 0;
}
int main(int argc, char* argv[])
{
int num = 1;
HANDLE hthread1,hthread2;
DWORD dwthreadid;
//char szBuff[MAX_PATH];
hthread1=CreateThread(NULL,0,clientthread,(LPVOID)num,0,&dwthreadid);
// if(hthread1==NULL)
// {
// printf("fail55/n");
// }
hthread2=CreateThread(NULL,0,clientthread2,(LPVOID)(num+1),0,&dwthreadid);
// if(hthread2==NULL)
// {
// printf("fail55/n");
// }
// gets(szBuff);
hMutex1 = CreateMutex(NULL,true,"mutext1");
::ReleaseMutex(hMutex1);
Sleep(7000);
CloseHandle(hthread1);
CloseHandle(hthread2);
return 0;
}