All pastes #58304 Raw Edit

blAckEnEd

public c v1 · immutable
#58304 ·published 2006-05-23 08:19 UTC
rendered paste body
// Semafor.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <windows.h>#include <stdio.h>int bag;int read_count;HANDLE hMapFile;LPVOID lpMapAddress;HANDLE Writing, Status;HANDLE CreateMap(HANDLE FileToBeMapped, LPCWSTR MapName){   HANDLE MapHandle;   MapHandle= CreateFileMapping(FileToBeMapped,                                NULL,                                PAGE_READWRITE,                                0,                                4096,                                MapName);   if (MapHandle == NULL)   {	   printf("error: CreateFileMapping!\n");      return(NULL);   }   else      return(MapHandle);}LPVOID MapView(HANDLE hMap){   LPVOID MappedPointer;   MappedPointer= MapViewOfFile(hMap,                                FILE_MAP_WRITE | FILE_MAP_READ,                                0, 0, 4096);   if (MappedPointer == NULL)   {	   printf("error: MapViewOfFile!\n");      return(NULL);   }   else      return(MappedPointer);}LPVOID ReadBytes(LPVOID from, LPVOID to, DWORD len){	return(memcpy(to,from,len));}LPVOID WriteBytes(LPVOID to, LPVOID from, DWORD len){	return(memcpy(to,from,len));}void writer(){		WaitForSingleObject(Writing, INFINITE);		ReadBytes(lpMapAddress, &bag, sizeof(int));		bag++;		WriteBytes(lpMapAddress, &bag, sizeof(int));		printf("am scris: %d\n", bag);		ReleaseMutex(Writing);//		Sleep(1000);}void reader(){	WaitForSingleObject(Status, INFINITE);	ReadBytes((int *)lpMapAddress+1, &read_count, sizeof(int));	read_count++;	WriteBytes((int *)lpMapAddress+1, &read_count, sizeof(int));	if (read_count == 1)		WaitForSingleObject(Writing, INFINITE);	ReadBytes(lpMapAddress, &bag, sizeof(int));	printf("am citit: %d\n", bag);	ReadBytes((int *)lpMapAddress + 1, &read_count, sizeof(int));	read_count--;	WriteBytes((int *)lpMapAddress + 1, &read_count, sizeof(int));	if (!read_count)		ReleaseMutex(Writing);	ReleaseMutex(Status);//	Sleep(500);}int _tmain(int argc, _TCHAR* argv[]){	bag = 1;	read_count = 0;	hMapFile = CreateMap((HANDLE) 0xFFFFFFFF, L"Warehouse");	lpMapAddress = MapView(hMapFile);//zona de memorie 		Writing = CreateMutex(NULL, TRUE, L"Writing");	if(GetLastError() != ERROR_ALREADY_EXISTS)	{		WriteBytes(lpMapAddress, &bag, sizeof(int));		ReleaseMutex(Writing);	}	Status = CreateMutex(NULL, TRUE, L"Status");	if(GetLastError() != ERROR_ALREADY_EXISTS)	{		WriteBytes((int *)lpMapAddress + 1, &read_count, sizeof(int));		ReleaseMutex(Status);	}	while (1)	{		writer ();		reader ();		writer ();		reader ();		Sleep (500);	}	return 0;}