#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <ctime>
int semaphoreImpl() {
srand((unsigned)time(NULL));
HANDLE fileMapping = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
sizeof(int),
L"SharedMemoryForInteger");
if (fileMapping == NULL) {
std::cerr << "Could not create file mapping object: " << GetLastError() << std::endl;
return 1;
}
int* sharedInt = (int*)MapViewOfFile(
fileMapping,
FILE_MAP_ALL_ACCESS,
0,
0,
sizeof(int));
if (sharedInt == NULL) {
std::cerr << "Could not map view of file: " << GetLastError() << std::endl;
CloseHandle(fileMapping);
return 1;
}
*sharedInt = 0;
HANDLE semaphore = CreateSemaphore(
NULL,
1,
1,
L"MySemaphore");
if (semaphore == NULL) {
std::cerr << "CreateSemaphore error: " << GetLastError() << std::endl;
UnmapViewOfFile(sharedInt);
CloseHandle(fileMapping);
return 1;
}
while (*sharedInt < 10) {
WaitForSingleObject(semaphore, INFINITE);
std::cout << "Incrementor1: Current value = " << *sharedInt << ". Incrementing..." << std::endl;
(*sharedInt)++;
Sleep(rand() % 1000 + 500);
ReleaseSemaphore(semaphore, 1, NULL);
}
UnmapViewOfFile(sharedInt);
CloseHandle(fileMapping);
CloseHandle(semaphore);
return 0;
}
int main() {
semaphoreImpl();
getchar();
return 0;
}
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <ctime>
int semaphoreImpl() {
srand((unsigned)time(NULL));
HANDLE fileMapping = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
sizeof(int),
L"SharedMemoryForInteger");
if (fileMapping == NULL) {
std::cerr << "Could not create file mapping object: " << GetLastError() << std::endl;
return 1;
}
int* sharedInt = (int*)MapViewOfFile(
fileMapping,
FILE_MAP_ALL_ACCESS,
0,
0,
sizeof(int));
if (sharedInt == NULL) {
std::cerr << "Could not map view of file: " << GetLastError() << std::endl;
CloseHandle(fileMapping);
return 1;
}
*sharedInt = 0;
HANDLE semaphore = CreateSemaphore(
NULL,
1,
1,
L"MySemaphore");
if (semaphore == NULL) {
std::cerr << "CreateSemaphore error: " << GetLastError() << std::endl;
UnmapViewOfFile(sharedInt);
CloseHandle(fileMapping);
return 1;
}
while (*sharedInt < 10) {
WaitForSingleObject(semaphore, INFINITE);
std::cout << "Incrementor1: Current value = " << *sharedInt << ". Incrementing..." << std::endl;
(*sharedInt)++;
Sleep(rand() % 1000 + 500);
ReleaseSemaphore(semaphore, 1, NULL);
}
UnmapViewOfFile(sharedInt);
CloseHandle(fileMapping);
CloseHandle(semaphore);
return 0;
}
int main() {
semaphoreImpl();
getchar();
return 0;
}