
ЛР-3 ОС
.docx
ФЕДЕРАЛЬНОЕ АГЕНТСТВО СВЯЗИ
Ордена Трудового Красного Знамени
федеральное государственное бюджетное образовательное учреждение
высшего образования
Московский технический университет связи и информатики
----------------------------------------------------------------------------------------------
Кафедра Математической кибернетики и информационных технологий
ЛАБОРАТОРНАЯ РАБОТА № 3
по дисциплине
ОПЕРАЦИОННЫЕ СИСТЕМЫ
«Методы синхронизация потоков»
Выполнил:
студентка Гончарова Екатерина
группа БФИ1601
Проверил:
Королькова Т.В.
ст. пр. кафедры МКиИТ
Дата 30.10.2018
Москва 2018
Название работы: Методы синхронизация потоков.
Цель работы: получение практических навыков по использованию Win32 API для синхронизации потоков.
Задание: Исследование на конкретном примере следующих методов синхронизации потоков:
критические секции;
мьютексы;
события.
Задачу для синхронизации выбрать на свое усмотрение.
Критическая секция
Исходный код:
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <thread>
using namespace std;
int global = 0;
#define pause() cout << "Press any key to continue..." << endl; _getch()
CRITICAL_SECTION cs;
void vivod(int k) {
EnterCriticalSection(&cs);
for (int i = 0; i < 10; i++) {
cout << k;
Sleep(50);
}
cout << endl;
LeaveCriticalSection(&cs);
}
int main()
{
InitializeCriticalSection(&cs);
int i, j;
HANDLE hThread;
DWORD IDThread;
thread thread1(vivod, 1);
thread thread2(vivod, 2);
thread thread3(vivod, 3);
thread thread4(vivod, 4);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
DeleteCriticalSection(&cs);
pause();
return 0;
}
Рисунок 1 - Результат выполнения программы
Мьютексы.
Исходный код:
#include "pch.h"
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <Windows.h>
#include <cstring>
struct SharedData {
int sch = 0;
char mas[16];
};
HANDLE mutex;
HANDLE mapping;
using namespace std;
int main() {
DWORD dwBytesWritten = 0;
HANDLE hFile = CreateFile(TEXT("test1.txt"), // name of the write
GENERIC_WRITE | GENERIC_READ, // open for reading and writing
FILE_SHARE_WRITE | FILE_SHARE_READ, // share for reading and writing
NULL, // default security
OPEN_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
mapping = CreateFileMappingA(hFile, nullptr, PAGE_READWRITE, 0, sizeof(SharedData), "first1");
unique_ptr<SharedData, decltype(&UnmapViewOfFile)> data(
(SharedData*)MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0),
UnmapViewOfFile);
mutex = OpenMutexA(MUTEX_ALL_ACCESS, TRUE, "first");
while (mutex == NULL) {
mutex = CreateMutexA(NULL, FALSE, "first");
}
cout << "hFile:" << hFile << endl;
cout << "mapping:" << mapping << endl;
cout << "mutex:" << mutex << endl;
DWORD dwBytesToWrite = 13;
//system("pause");
thread user_input_thread([&] {
WaitForSingleObject(mutex, INFINITE);
for (int i = 0; i < 4; i++) {
data->mas[data->sch] = '9';
cout << "mas[" << data->sch << "]= " << data->mas[data->sch] << " ";
WriteFile(
hFile, // open file handle
(LPCVOID)data->mas[data->sch], // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL);
Sleep(500);
data->sch++;
}
ReleaseMutex(mutex);
});
user_input_thread.join();
system("pause");
CloseHandle(hFile);
}
>>>>>>>>>>>
Следующая программа:
#include "pch.h"
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <Windows.h>
#include <cstring>
struct SharedData {
int sch = 0;
char mas[16];
};
HANDLE mutex;
HANDLE mapping;
using namespace std;
int main() {
DWORD dwBytesWritten = 0;
HANDLE hFile = CreateFile(TEXT("test1.txt"), // name of the write
GENERIC_WRITE | GENERIC_READ, // open for reading and writing
FILE_SHARE_WRITE | FILE_SHARE_READ, // share for reading and writing
NULL, // default security
OPEN_ALWAYS, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
mapping = CreateFileMappingA(hFile, nullptr, PAGE_READWRITE, 0, sizeof(SharedData), "first1");
unique_ptr<SharedData, decltype(&UnmapViewOfFile)> data(
(SharedData*)MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0),
UnmapViewOfFile);
mutex = OpenMutexA(MUTEX_ALL_ACCESS, TRUE, "first");
if (mutex == NULL) {
mutex = CreateMutexA(NULL, FALSE, "first");
}
cout << "hFile:" << hFile << endl;
cout << "mapping:" << mapping << endl;
cout << "mutex:" << mutex << endl;
DWORD dwBytesToWrite = 13;
//system("pause");
thread user_input_thread([&] {
WaitForSingleObject(mutex, INFINITE);
for (int i = 0; i < 4; i++) {
data->mas[data->sch] = '3';
cout << "mas[" << data->sch << "]= " << data->mas[data->sch] << " ";
WriteFile(
hFile, // open file handle
(LPCVOID)data->mas[data->sch], // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL);
Sleep(500);
data->sch++;
}
ReleaseMutex(mutex);
});
user_input_thread.join();
system("pause");
CloseHandle(hFile);
}
Рисунок 2 - результат работы мьютексов
Событие.
Исходный код:
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <thread>
#include <string.h>
#include <cstring>
using namespace std;
HANDLE hEvent = NULL;
int main()
{
char c[2];
char yes[2]="Y";
hEvent = CreateEventA(NULL, TRUE, FALSE, "check");
cout << "Are you ready? Y/N" << endl;
cin.getline(c, 2);
if (strcmp(c, yes) == 0) {
SetEvent(hEvent);
cout << "Let's go!\n";
}
else {
cout << "Okey :(\n";
}
system("pause");
}
>>>>>>>>>>>>>>>>>
Следующая программа:
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <thread>
#include <string.h>
#include <cstring>
CRITICAL_SECTION cs;
using namespace std;
int a=0;
HANDLE Event = NULL;
void vivod(int sch) {
WaitForSingleObject(Event, INFINITE);
EnterCriticalSection(&cs);
for (int i = 0; i < 5; i++) {
a += sch;
cout << a << " ";
Sleep(250);
}
cout << endl;
LeaveCriticalSection(&cs);
}
int main()
{
InitializeCriticalSection(&cs);
Event = OpenEventA(EVENT_ALL_ACCESS, FALSE, "check");
thread thr1(vivod, -1);
thread thr2(vivod, 1);
thread thr3(vivod, -1);
thread thr4(vivod, 1);
thr1.join();
thr2.join();
thr3.join();
thr4.join();
ResetEvent(Event);
CloseHandle(Event);
cout << endl;
system("pause");
}
Рисунок 3 - результат работы события