?? sharedll.cpp
字號:
// ShareDll.cpp : 定義 DLL 應用程序的入口點。
//
// Chen Danwei 2005-10-1
//
// for the demo of PV opreation in OS classe
//
//pls contact with chendanwei@hotmail.com if any question about it
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "windows.h"
#include "winnt.h"
//here we wana to export lib
#define __SHAREDLLLIB extern "C" __declspec(dllexport)
#include "ShareDllLib.h"
#define MAXBUFFNUM 8
#pragma data_seg("DvShareData")
//for count the instance
LONG glInstanceCounter = 0;
//pointer of writer and reader
int pWriter = 0;
int pReader = 0;
#pragma data_seg()
//to allocate the glob buffer in the DvShareData section
__declspec(allocate("DvShareData")) LONG glBuffer[MAXBUFFNUM];
//to share the section DvShareData
#pragma comment(linker, "/SECTION:DvShareData,RWS")
//a mutex between the producer and the customer
HANDLE hMutex = NULL;
//semphore for producer
HANDLE hSemP = NULL;
//semphore for customer
HANDLE hSemC = NULL;
//some local function
static void IniatGlobParameter();
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
++glInstanceCounter;
printf(" %d process attatch ........\n", glInstanceCounter);
IniatGlobParameter();
if( 1 == glInstanceCounter) //attatch to the first process, so iniate the glob parameter
{
int i = 0;
while( i < MAXBUFFNUM )
{
glBuffer[i] = 0;
++i;
}
}
break;
case DLL_THREAD_ATTACH:
printf("thread attach module \n");
break;
case DLL_THREAD_DETACH:
printf("thread detach module \n");
break;
case DLL_PROCESS_DETACH:
printf("process detah module \n");
--glInstanceCounter;
CloseHandle(hMutex);
CloseHandle(hSemP);
CloseHandle(hSemC);
break;
}
return TRUE;
}
void IniatGlobParameter()
{
__try
{
hMutex = CreateMutex(NULL, false, "ChenDanweiOsClassMutex");
hSemP = CreateSemaphore(NULL, MAXBUFFNUM, MAXBUFFNUM, "ChenDanweiOsClassSemP");
hSemC = CreateSemaphore(NULL, 0, MAXBUFFNUM, "ChenDanweiOsClassSemC");
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
printf(" exception in creatting mutex or semphore !!\n");
__try
{
CloseHandle(hMutex);
CloseHandle(hSemP);
CloseHandle(hSemC);
}
__finally
{
exit(0);
}
}
return;
}
int WriteBuffer( IN long & aData)
{
int ret = 0 ;
__try
{
WaitForSingleObject(hSemP,INFINITE);
WaitForSingleObject(hMutex,INFINITE); //simlar to P operate
glBuffer[pWriter] = aData;
pWriter = (pWriter + 1) % MAXBUFFNUM;
}
__finally //whatever condition, we should re
{
ReleaseMutex(hMutex);
ReleaseSemaphore(hSemC, 1, NULL);
}
return ret;
}
int ReadBuffer( OUT long & aData)
{
int ret = 0;
__try
{
WaitForSingleObject(hSemC,INFINITE); //simlar to P operate
WaitForSingleObject(hMutex,INFINITE);
aData = glBuffer[pReader];
pReader = (pReader + 1) % MAXBUFFNUM;
}
__finally //whatever condition, we should release
{
ReleaseMutex(hMutex); //simlar to V oprerate
ReleaseSemaphore(hSemP, 1, NULL);
}
return ret;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -