// L3.cpp: определяет точку входа для консольного приложения.
//

#include "stdafx.h"
#include<iostream>
#include<windows.h>
#include<conio.h>
#include <stdio.h>
//#include "afxmt.h"
#include <tchar.h>

using namespace std;

# define BUF_SIZE 5

class CMyCritSectClass
{
	HANDLE hMap;
	int i;
public:
	
	HANDLE mutex;   
	CMyCritSectClass() 
	{
		i = 1;
		hMap = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 100, TEXT("filemapping")); 
		HANDLE mutex = CreateMutex(NULL, FALSE, TEXT("Mutex"));	
	}
	/*
	~CMyCritSectClass(void)
	{
		CloseHandle (hMap);
	}
	*/
    void firstMethod(void)
	{
		WaitForSingleObject(mutex, INFINITE);
		LPCTSTR pBuf;
		TCHAR szMsg[5];
		wsprintf(szMsg,L"%d",i);

        pBuf = (LPTSTR) MapViewOfFile (hMap, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);   
		CopyMemory ((PVOID) pBuf, szMsg, (5 * sizeof (TCHAR)));
		wcout << L"First write " << i << endl;
		i++;
		Sleep(100);
		ReleaseMutex(mutex);
	}

	void secondMethod(void)
	{
		WaitForSingleObject(mutex, INFINITE);
		LPCTSTR pBuf;
		TCHAR szMsg[5];


		pBuf = (LPTSTR) MapViewOfFile (hMap, FILE_MAP_ALL_ACCESS, 0, 0,  BUF_SIZE); 
		TCHAR buf[64];
		DWORD dwValue = GetCurrentThreadId();
		wcout << L"Second read " << pBuf << endl;
		ReleaseMutex(mutex);
	}
};


int _tmain(int argc, _TCHAR* argv[])
{
	CMyCritSectClass example;
	
		
	if(argc==1)
	{	STARTUPINFO si = { sizeof(si) };
		PROCESS_INFORMATION pi; 
		TCHAR zb[]=TEXT("abcd.txt sd");
		BOOL b;
		b = CreateProcess(TEXT("L3.exe"), zb , NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
		if (b == FALSE)
		{
			cout << "Cannot create process" << endl << GetLastError() << endl;
			getch();
			return 0;
			//exit( 1 );
		}
		
		for(int i = 0; i < 10; i++)
		{
			
			example.firstMethod();
			//cout << "process 1 " <<i<< endl;
			
			Sleep(50);
		}
		WaitForSingleObject(pi.hProcess, INFINITE);
		CloseHandle(pi.hProcess);
	}
	else
	{
		//Sleep(100);
		
		for(int i = 0; i < 10; i++)
		{
			Sleep(70);
			
			example.secondMethod();
			//cout << "process 2 " <<i<< endl;
		
		}
		getch();
	}

	
	

	return 0;
}

Соседние файлы в папке Лаба 3
  • #
    15.06.20142.18 Кб59L3.cpp
  • #
    15.06.20144.17 Mб59L3.ncb
  • #
    15.06.2014870 б60L3.sln
  • #
    15.06.201412.29 Кб59L3.suo
  • #
    15.06.20144.52 Кб59L3.vcproj
  • #
    15.06.20145.17 Кб59L3.vcxproj