Linux kernel modulesDheryta JaisinghaniMost of this session will focus on Kernel Module Programming. We will briefly talk about the interaction of different layers of operating system from userspace to kernel space. Starting from simple Hello World kernel modules, we will learn the development of more sophisticated modules related to device drivers and interrupt handlers. We will also briefly touch upon the shell scripts and how they can be used to extract system level information. Since, this will be a hands on session, attendees are expected to try the examples on their machines. Basic understanding of operating systems and C programming is expected for the tutorial.
Sistemas Operacionais Modernos - Gerenciamento de MemóriaWellington OliveiraO documento discute técnicas de gerenciamento de memória em sistemas operacionais, incluindo paginação, substituição de páginas, memória virtual e algoritmos relacionados. Aborda conceitos como tabelas de páginas, algoritmos como FIFO, LRU e Clock para substituição de páginas, e questões de projeto como tamanho de página e políticas de alocação e limpeza.
Sistemas Operacionais - Aula 08 (Sincronização e Comunicação entre Processos)Leinylson FontineleO documento discute sincronização e comunicação entre processos em sistemas operacionais. Apresenta os conceitos de aplicações concorrentes e a necessidade de sincronização quando processos compartilham recursos. Discutem problemas que podem ocorrer em aplicações bancárias que manipulam contas correntes de forma concorrente e soluções como exclusão mútua.
Cs8493 unit 5Kathirvel AyyaswamyThe document discusses the Linux operating system, including its history, design principles, kernel modules, process management, scheduling, memory management, input/output management, file systems, and inter-process communication. It also briefly covers the architectures and frameworks of two popular mobile operating systems, iOS and Android. The document provides details on Linux kernel versions and distributions, and explains concepts like kernel synchronization, interrupt handling, and the Completely Fair Scheduler algorithm used in Linux.
Bootloader and bootloadingArpita Gupta1. The booting process begins with the BIOS performing checks and finding a bootable device from which to load an operating system. It loads the master boot record which contains the boot loader like GRUB.
2. The boot loader loads the Linux kernel from the hard disk into memory and passes control to it. The kernel then launches the init process to perform startup tasks and launch other processes.
3. Init controls the runlevels which determine the system configuration and processes that are running. It is responsible for system startup and shutdown processes.
Windows ArchitectureAmrith KrishnaA presentation on microsoft windows architecture.
Discusses
Internal architecture
Kernel
Executive
User processes
Histor
Monolithic kernel vs. MicrokernelRQK KhanThe document compares monolithic and microkernel operating system architectures. A monolithic kernel runs all system services in kernel space, while a microkernel reduces the kernel to basic process communication and I/O control, running other services like memory management in user space as servers. Microkernels have advantages in extensibility, portability and stability due to smaller kernel size, while monolithic kernels have advantages in performance due to running more in kernel space. Examples of each type of kernel are given.
Resumo de S.O.dannas_06Este documento apresenta uma introdução sobre sistemas operacionais em menos de 3 frases:
O documento discute a história e evolução dos sistemas operacionais, desde as primeiras gerações baseadas em válvulas até os sistemas modernos da quinta geração com foco na computação ubíquita. Também resume os principais componentes de hardware de computadores e conceitos-chave de sistemas operacionais como processos, memória, E/S e chamadas ao sistema.
Kernel (computing)Teja BheemanapallyThe kernel is the central component of most computer operating systems. It acts as a bridge between applications and hardware, managing system resources and communication. Kernels can be categorized as monolithic, micro, hybrid, or exokernel based on how operating system services are implemented. A monolithic kernel executes all services together, while a microkernel runs most in user space for modularity. Hybrid kernels combine aspects of both.
UnixErm78The document provides an overview of the UNIX operating system. It discusses the history and development of UNIX from the 1960s onward. It describes the key features of UNIX including its layered architecture, kernel, shell, process management, file system, and security features. It also covers basic UNIX commands for working with files and directories, permissions, and getting help. The objective is to introduce readers to fundamental concepts of the UNIX OS.
2009 1 - sistemas operacionais - aula 3 - processosComputação DepressãoO documento discute processos e threads em sistemas operacionais. Aborda conceitos como criação e término de processos, hierarquia de processos, estados de processos e implementação de processos através de tabelas de processos e contexto de hardware e software.
Linux Memory ManagementSuvendu Kumar DashLinux Memory Management
1.Memory Structure of Linux OS.
2.How Program is loaded into the memory.
3.Address Translation.
4.Feature for Multithreading and Multiprocessing.
Hacking QNXricardomcmRicardo Mourato gave a presentation on hacking the QNX RTOS. Some key points:
- QNX is a real-time operating system used in embedded systems like medical devices, robots, and cars. It has a microkernel architecture for reliability.
- Potential vulnerabilities were demonstrated, like exploiting default services like Telnet and FTP to gain root access, or abusing the QCONN debugging protocol.
- The Qnet inter-process communication could allow accessing resources like files and processes remotely in a transparent way.
- A live demonstration showed exploiting these avenues to hack into a QNX system remotely or locally. Default configurations and services provide initial access points to attack the system.
Free bsdDianaEste documento proporciona una introducción a FreeBSD, un sistema operativo derivado de BSD. Explica que FreeBSD está basado en la versión 4.4 BSD-Lite y fue desarrollado por la Universidad de California en Berkeley. También describe algunas características clave de FreeBSD como que es multiusuario, compatible con múltiples procesadores, y ofrece niveles de seguridad y capacidades de firewall integradas.
NTFS file systemRavi YasasNTFS is a file system introduced by Microsoft in 1993 for Windows NT operating systems. It improved on previous file systems with features like larger storage capacity support, redundancy, security, and performance improvements important for businesses. NTFS formats volumes with system files including the Master File Table that stores metadata for all files and folders. It provides security, compression, encryption and other advanced features through file attributes. NTFS also supports features like sparse files, recoverability, and alternate data streams.
Chapter 7talhashahid40This document summarizes input/output (I/O) and discusses I/O problems, I/O modules, external devices, typical I/O data rates, and I/O module functions. It then describes I/O module control and timing, processor communication, device communication, and I/O techniques including programmed I/O, interrupt-driven I/O, and direct memory access (DMA).
4 threadsDr. Loganathan RThreads allow a process to concurrently perform multiple tasks. A thread is the basic unit of CPU utilization and shares resources with other threads in the same process. Multithreading improves responsiveness, allows resource sharing, and enables better utilization of multiprocessor systems. There are different models for mapping user threads to kernel threads, including many-to-one, one-to-one, and many-to-many. Popular thread libraries include Pthreads and Windows threads which provide APIs for thread management. Issues with multithreading include how to handle signals, cancellation, and the fork and exec system calls across threads.
linux device driverRahul BatraLinux device drivers act as an interface between hardware devices and user programs. They communicate with hardware devices and expose an interface to user applications through system calls. Device drivers can be loaded as kernel modules and provide access to devices through special files in the /dev directory. Common operations for drivers include handling read and write requests either through interrupt-driven or polling-based I/O.
Process scheduling linuxDr. C.V. Suresh BabuLinux uses a preemptive multilevel feedback queue scheduling algorithm. Processes have both static priorities based on nice values and dynamic priorities based on recent CPU usage. The scheduler selects from two lists of active and expired processes using their dynamic priorities. It also performs load balancing across CPU runqueues to improve performance on multiprocessor systems. System calls like setpriority(), sched_setscheduler(), and sched_yield() allow modifying process priorities and scheduling policies.
Linux Kernel - Virtual File SystemAdrian HuangVirtual File System in Linux Kernel
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
SAMPATSampath PiriyaPiriya Sampath is seeking opportunities for career growth in an organization that provides learning and development. He has a B.Tech in computer science with 62% marks and skills in Java, SQL, C, Eclipse IDE. A project involved proposing a method for private and secure location-based queries using oblivious transfer and prevent information retrieval. He completed Java and J2EE training and participated in workshops on robotics and quizzes.
Linux kernel modulesDheryta JaisinghaniMost of this session will focus on Kernel Module Programming. We will briefly talk about the interaction of different layers of operating system from userspace to kernel space. Starting from simple Hello World kernel modules, we will learn the development of more sophisticated modules related to device drivers and interrupt handlers. We will also briefly touch upon the shell scripts and how they can be used to extract system level information. Since, this will be a hands on session, attendees are expected to try the examples on their machines. Basic understanding of operating systems and C programming is expected for the tutorial.
Sistemas Operacionais Modernos - Gerenciamento de MemóriaWellington OliveiraO documento discute técnicas de gerenciamento de memória em sistemas operacionais, incluindo paginação, substituição de páginas, memória virtual e algoritmos relacionados. Aborda conceitos como tabelas de páginas, algoritmos como FIFO, LRU e Clock para substituição de páginas, e questões de projeto como tamanho de página e políticas de alocação e limpeza.
Sistemas Operacionais - Aula 08 (Sincronização e Comunicação entre Processos)Leinylson FontineleO documento discute sincronização e comunicação entre processos em sistemas operacionais. Apresenta os conceitos de aplicações concorrentes e a necessidade de sincronização quando processos compartilham recursos. Discutem problemas que podem ocorrer em aplicações bancárias que manipulam contas correntes de forma concorrente e soluções como exclusão mútua.
Cs8493 unit 5Kathirvel AyyaswamyThe document discusses the Linux operating system, including its history, design principles, kernel modules, process management, scheduling, memory management, input/output management, file systems, and inter-process communication. It also briefly covers the architectures and frameworks of two popular mobile operating systems, iOS and Android. The document provides details on Linux kernel versions and distributions, and explains concepts like kernel synchronization, interrupt handling, and the Completely Fair Scheduler algorithm used in Linux.
Bootloader and bootloadingArpita Gupta1. The booting process begins with the BIOS performing checks and finding a bootable device from which to load an operating system. It loads the master boot record which contains the boot loader like GRUB.
2. The boot loader loads the Linux kernel from the hard disk into memory and passes control to it. The kernel then launches the init process to perform startup tasks and launch other processes.
3. Init controls the runlevels which determine the system configuration and processes that are running. It is responsible for system startup and shutdown processes.
Windows ArchitectureAmrith KrishnaA presentation on microsoft windows architecture.
Discusses
Internal architecture
Kernel
Executive
User processes
Histor
Monolithic kernel vs. MicrokernelRQK KhanThe document compares monolithic and microkernel operating system architectures. A monolithic kernel runs all system services in kernel space, while a microkernel reduces the kernel to basic process communication and I/O control, running other services like memory management in user space as servers. Microkernels have advantages in extensibility, portability and stability due to smaller kernel size, while monolithic kernels have advantages in performance due to running more in kernel space. Examples of each type of kernel are given.
Resumo de S.O.dannas_06Este documento apresenta uma introdução sobre sistemas operacionais em menos de 3 frases:
O documento discute a história e evolução dos sistemas operacionais, desde as primeiras gerações baseadas em válvulas até os sistemas modernos da quinta geração com foco na computação ubíquita. Também resume os principais componentes de hardware de computadores e conceitos-chave de sistemas operacionais como processos, memória, E/S e chamadas ao sistema.
Kernel (computing)Teja BheemanapallyThe kernel is the central component of most computer operating systems. It acts as a bridge between applications and hardware, managing system resources and communication. Kernels can be categorized as monolithic, micro, hybrid, or exokernel based on how operating system services are implemented. A monolithic kernel executes all services together, while a microkernel runs most in user space for modularity. Hybrid kernels combine aspects of both.
UnixErm78The document provides an overview of the UNIX operating system. It discusses the history and development of UNIX from the 1960s onward. It describes the key features of UNIX including its layered architecture, kernel, shell, process management, file system, and security features. It also covers basic UNIX commands for working with files and directories, permissions, and getting help. The objective is to introduce readers to fundamental concepts of the UNIX OS.
2009 1 - sistemas operacionais - aula 3 - processosComputação DepressãoO documento discute processos e threads em sistemas operacionais. Aborda conceitos como criação e término de processos, hierarquia de processos, estados de processos e implementação de processos através de tabelas de processos e contexto de hardware e software.
Linux Memory ManagementSuvendu Kumar DashLinux Memory Management
1.Memory Structure of Linux OS.
2.How Program is loaded into the memory.
3.Address Translation.
4.Feature for Multithreading and Multiprocessing.
Hacking QNXricardomcmRicardo Mourato gave a presentation on hacking the QNX RTOS. Some key points:
- QNX is a real-time operating system used in embedded systems like medical devices, robots, and cars. It has a microkernel architecture for reliability.
- Potential vulnerabilities were demonstrated, like exploiting default services like Telnet and FTP to gain root access, or abusing the QCONN debugging protocol.
- The Qnet inter-process communication could allow accessing resources like files and processes remotely in a transparent way.
- A live demonstration showed exploiting these avenues to hack into a QNX system remotely or locally. Default configurations and services provide initial access points to attack the system.
Free bsdDianaEste documento proporciona una introducción a FreeBSD, un sistema operativo derivado de BSD. Explica que FreeBSD está basado en la versión 4.4 BSD-Lite y fue desarrollado por la Universidad de California en Berkeley. También describe algunas características clave de FreeBSD como que es multiusuario, compatible con múltiples procesadores, y ofrece niveles de seguridad y capacidades de firewall integradas.
NTFS file systemRavi YasasNTFS is a file system introduced by Microsoft in 1993 for Windows NT operating systems. It improved on previous file systems with features like larger storage capacity support, redundancy, security, and performance improvements important for businesses. NTFS formats volumes with system files including the Master File Table that stores metadata for all files and folders. It provides security, compression, encryption and other advanced features through file attributes. NTFS also supports features like sparse files, recoverability, and alternate data streams.
Chapter 7talhashahid40This document summarizes input/output (I/O) and discusses I/O problems, I/O modules, external devices, typical I/O data rates, and I/O module functions. It then describes I/O module control and timing, processor communication, device communication, and I/O techniques including programmed I/O, interrupt-driven I/O, and direct memory access (DMA).
4 threadsDr. Loganathan RThreads allow a process to concurrently perform multiple tasks. A thread is the basic unit of CPU utilization and shares resources with other threads in the same process. Multithreading improves responsiveness, allows resource sharing, and enables better utilization of multiprocessor systems. There are different models for mapping user threads to kernel threads, including many-to-one, one-to-one, and many-to-many. Popular thread libraries include Pthreads and Windows threads which provide APIs for thread management. Issues with multithreading include how to handle signals, cancellation, and the fork and exec system calls across threads.
linux device driverRahul BatraLinux device drivers act as an interface between hardware devices and user programs. They communicate with hardware devices and expose an interface to user applications through system calls. Device drivers can be loaded as kernel modules and provide access to devices through special files in the /dev directory. Common operations for drivers include handling read and write requests either through interrupt-driven or polling-based I/O.
Process scheduling linuxDr. C.V. Suresh BabuLinux uses a preemptive multilevel feedback queue scheduling algorithm. Processes have both static priorities based on nice values and dynamic priorities based on recent CPU usage. The scheduler selects from two lists of active and expired processes using their dynamic priorities. It also performs load balancing across CPU runqueues to improve performance on multiprocessor systems. System calls like setpriority(), sched_setscheduler(), and sched_yield() allow modifying process priorities and scheduling policies.
Linux Kernel - Virtual File SystemAdrian HuangVirtual File System in Linux Kernel
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
SAMPATSampath PiriyaPiriya Sampath is seeking opportunities for career growth in an organization that provides learning and development. He has a B.Tech in computer science with 62% marks and skills in Java, SQL, C, Eclipse IDE. A project involved proposing a method for private and secure location-based queries using oblivious transfer and prevent information retrieval. He completed Java and J2EE training and participated in workshops on robotics and quizzes.
Vemma Premier clubAbiodun FawoleWhat's Possible with a Vemma Business?
It’s all up to you!
Since our start in 2004, the Vemma mission has remained strong — making a positive difference starts with people helping people. Vemma’s premium products are the cornerstone for optimal health and they’re helping people all over the world discover improved health and even a solid business opportunity. Share premium Vemma products with others and earn free product or, put the pedal to the metal and discover the power of affiliate marketing.
Either way, you’re in the driver’s seat.
So, whether you want to get your Vemma products for free, create a side income to help with the bills, get out of debt, exchange the traditional 9 to 5 for your own schedule, or all of the above, the Vemma business opportunity can help you achieve it.
It's about you, and we are ready to help!
Scada functionsSundarapandy PillaiThe document discusses the technical functions of a SCADA system. It describes data acquisition as the basic function that collects telemetry measurements and status indications from devices like CTs and PTs through RTUs and IEDs. Data is stored in a real-time database and acquired in less than 2 seconds. Other key functions include supervisory control that allows remote control of devices, tagging for authorization of device operations, alarms to notify of events, logging to record operations and alarms, load shedding for automatic or manual load control during emergencies, and trending to plot measurements over time. The SCADA system provides the operator complete visibility of the power system from a central control room.
BAKTERIOLOGI - SISTEM PERNAFASANMuhammad NasrullahDokumen tersebut membahas tentang bakteriologi penyakit sistem pernafasan, termasuk bakteri yang menyebabkan infeksi tenggorokan, trakea, bronkus, dan paru-paru serta cara diagnosa makmal melalui pemeriksaan Gram, kultur, dan tes serologi. Bakteri utama yang dibahas adalah Streptococcus pyogenes, Corynebacterium diphtheriae, Fusobacterium, Bordetella pertussis, Haemophilus influenzae, Streptococcus pneumoniae, Klebsiel
Z13 updateStig QuistgaardThe document summarizes the IBM z Systems z13 mainframe update. Key points include the status of IBM servers and trends in digital disruption driving increased mainframe requirements. The z13 launch is highlighted as enabling lower costs through improvements like simultaneous multithreading and large memory capabilities. Mainframes are described as the platform for the future, processing a growing number of mobile transactions worldwide and supporting a large portion of critical applications.
CARDIAC ARREST - JANTUNG TERHENTIMuhammad NasrullahPengenalan asas mengenai CARDIAC ARREST - JANTUNG TERHENTI
Contrato de servicios slidesharejegvastorgaEl documento habla sobre la Ley de Contratos del Sector Público. Explica brevemente su historia y regulación jurídica, así como conceptos clave como objeto, categorías, regulación armonizada, tramitación del expediente, singularidades, ejecución, modificación, extinción y responsabilidad del contratista. También menciona la Directiva 2004/18/CE y su transposición a la legislación española a través de la Ley de Contratos del Sector Público.
Fabelaydiana analisisErnestoFabela1196Este documento presenta datos sobre los niveles educativos en tres estados de la India (Haryana, Bihar y Uttar Pradesh). Calcula el valor de chi cuadrada para comparar los valores observados con los esperados. El valor obtenido de chi cuadrada es 63.301, mayor que el valor crítico de la tabla para un nivel de significancia del 0.05. Por lo tanto, se rechaza la hipótesis nula de que los niveles educativos son los mismos entre los estados, y se concluye que los niveles educativos difieren significativ
prescription errors raise concern over electronic records libertyvilleElectronic health records may have the potential to help make healthcare more efficient andpatient histories more readily available. For more details Visit: libertyvillepersonalinjurylawyer.com/
The little history of the pizzarosavelayosThe pizza originated in Naples, Italy. The Margherita pizza was created for Queen Margherita of Savoy by Raffaelle Exposito, using tomato sauce, cheese, and basil to represent the colors of the Italian flag. The document proceeds to list the main ingredients to make a Margherita pizza: flour, water, olive oil, yeast, salt, tomato sauce, and cheese.
List of AbbreviationsDelta LaceyThe document lists common abbreviations, symbols, and dose designations that are frequently misinterpreted and involved in medication errors from the Institute for Safe Medication Practices (ISMP). It provides examples of errors and recommends alternatives to improve patient safety. Specifically, it details how abbreviations intended to represent things like medical terms, drug names, doses, or units of measurement are often misinterpreted, which can lead to overdoses or other medication mistakes. The ISMP compiled the list from reported errors to help standardize safe practices and terminology used in prescribing, dispensing, and administering medications.
ASPEK HUKUM PRAKTIK KEPERAWATAN PROFESIONALpjj_kemenkesDokumen tersebut membahas tentang aspek hukum dalam praktik keperawatan profesional di Indonesia, mencakup pengertian hukum kesehatan dan keperawatan, tujuan, sifat, dan sumber-sumber hukum yang relevan bagi keperawatan. Dokumen ini juga menjelaskan konsep-konsep hukum penting yang perlu diketahui oleh perawat.
Social Sciences & Humanities Across the SC5 WP2016/17 – Paul KilkennyEnvironmental Protection Agency, IrelandPresentation given by Paul Kilkenny, Irish Research Council, at the 2015 Horizon 2020 SC5 Information Day, 21/10/2015, Herbert Park Hotel, Dublin
INTESTINAL OBSTRUCTIONMuhammad NasrullahThis document discusses intestinal obstruction, defined as a blockage of the forward passage of food, waste, and gas through the intestines. It classifies and describes the etiology, pathophysiology, clinical manifestations, diagnostic evaluation, differential diagnosis, management, and complications of intestinal obstruction according to age, site of obstruction, and mechanical vs. functional causes. Key points include various causes of obstruction like hernias, adhesions, tumors, intussusception; symptoms of abdominal pain, vomiting, distension; and treatments including conservative management with NBM and IV fluids or surgical intervention like laparotomy.
Criatividade e ruturasAna BarreirosO documento discute as transformações na criação artística durante o século XIX, especificamente a emancipação dos artistas em relação às encomendas e o aparecimento de um mercado privado, levando ao surgimento de museus para exibir obras de arte.
2. 2/19Лекція 6
План лекції
Проблема синхронізації
Гонки (змагання)
Критична секція
Атомарні операції
Блокування, змінна блокування
Семафори
Задача виробник-споживач
Взаємні блокування
М’ютекси, умовні змінні, монітори
3. 3/19Лекція 6
Проблема синхронізації:
приклад
Нехай 2 потоки TA і TB (різних користувачів) отримують доступ до
деякого спільного ресурсу (банківський рахунок) з метою внесення
змін
На рахунку 100 у.о.
Користувач А намагається зняти 50 у.о.
Користувач В намагається покласти ще 100 у.о.
Алгоритм роботи потоків: total_amount = total_amount + new_amount;
1. Зчитати значення total_amount ( var1 = total_amount )
2. Обчислити нове значення total_amount ( var1 = var1 + new_amount )
3. Записати нове значення total_amount ( total_amount = var1 )
Послідовність подій:
1. ТА зчитав total_amount var1A = 100
2. ТА обчислив total_amount var1A = 100 – 50
3. ТА записав total_amount total_amount = 50
4. ТВ зчитав total_amount var1B = 50
5. ТВ обчислив total_amount var1B = 50 + 100
6. ТВ записав total_amount total_amount = 150
Все вірно
4. 4/19Лекція 6
Проблема синхронізації:
приклад (продовження)
Але результат може бути іншим!
Послідовність подій 2:
1. ТА зчитав total_amount var1A = 100
2. ТА обчислив total_amount var1A = 100 – 50
3. ТВ зчитав total_amount var1B = 100
4. ТВ обчислив total_amount var1B = 100 + 100
5. ТВ записав total_amount total_amount = 200
6. ТА записав total_amount total_amount = 50
В результаті total_amount == 50 (втрачена покладена сума)
Послідовність подій 3:
1. ТА зчитав total_amount var1A = 100
2. ТВ зчитав total_amount var1B = 100
3. ТВ обчислив total_amount var1B = 100 + 100
4. ТА обчислив total_amount var1A = 100 – 50
5. ТА записав total_amount total_amount = 50
6. ТВ записав total_amount total_amount = 200
В результаті total_amount == 200 (сума не знята)
5. 5/19Лекція 6
Деякі означення
Ситуація, коли 2 чи більше потоків обробляють
спільні поділювані дані, і кінцевий результат
залежить від співвідношення швидкостей потоків,
називається гонками або змаганням (race
condition)
Критична секція (critical section) – частина
програми, в якій здійснюється доступ до
поділюваних даних або ресурсу
Щоби виключити гонки, у критичній секції, пов'язаній з
певним ресурсом, повинно знаходитись не більше 1 потоку
Атомарна операція – така послідовність дій, яка
гарантовано виконується від початку до кінця без
втручання інших потоків (тобто, є неподільною)
Найпростіша реалізація – потік, що знаходиться у
критичній секції, забороняє усі переривання
Це неприйнятно, оскільки внаслідок збою у критичній секції
уся система може залишитись у непрацездатному стані
6. 6/19Лекція 6
Блокування
Блокування (locks) – це механізм, який
не дозволяє більше як одному потокові
виконувати код критичної секції
Найпростіша (наївна) реалізація
блокування – вводимо змінну блокування
F(D) (1 – вільно, 0 – зайнято)
Алгоритм спін-блокування (spinlock)
Здійснюємо опитування у циклі, доки не
виявимо, що ресурс вільний – так зване
активне очікування (busy waiting)
Встановлюємо відповідне значення
змінної блокування і займаємо ресурс
Проблема реалізації – операція
перевірка-встановлення має бути
атомарною (необхідна апаратна
підтримка)
Суттєвий недолік алгоритму –
нераціональні витрати процесорного
часу
Ресурс
вільний,
F(D)==1?
Зайняти ресурс,
F(D)=0
ні
так
Критична секція
ресурсу D
Звільнити ресурс,
F(D)=1
7. 7/19Лекція 6
Апарат подій для роботи
з критичними секціями
Функція WAIT(D)
переводить потік у стан
очікування події звільнення
ресурсу D
Функція POST(D)
викликається після
звільнення ресурсу D і
переводить усі потоки, що
його очікують, у стан
готовності (планувальник
обере один з них на
виконання)
У POSIX – виклики sleep() і
wakeup()
Проблема: накладні
витрати ОС на здійснення
викликів можуть
перевищити економію
(іноді активне очікування
раціональніше)
Критична секція
ресурсу D
Ресурс
вільний,
F(D)==1?
Зайняти ресурс,
F(D)=0
ні
так
Звільнити ресурс,
F(D)=1
Перевести потік
у стан очікування
ресурсу D
Перевести потік,
що очікує ресурс D,
у стан готовності
LeaveCriticalSection()
EnterCriticalSection()
8. 8/19Лекція 6
Семафори
Семафор (semaphore) – цілочисловий невід'ємний
лічильник (позначають S)
Для семафора визначені дві атомарні операції
V(S) {
S++;
if (waiting_threads()) POST(S);
}
P(S) {
if (S > 0) S--;
else WAIT(S);
}
Окремий випадок: якщо семафор може приймати
лише значення 0 і 1 (двійковий семафор), він
фактично є змінною блокування
Семафор – універсальний засіб, що забезпечує як
взаємне виключення, так і очікування події
9. 9/19Лекція 6
Задача виробник-споживач
Потік-виробник створює об’єкти і поміщає їх у буфер.
Операція розміщення об'єкта не є атомарною
Потік-споживач отримує об’єкти і видаляє їх з буфера.
Операція видалення об'єкта не є атомарною
Буфер має фіксовану довжину N
Вимоги:
1. Коли виробник або споживач працює з буфером, усі інші
потоки повинні чекати завершення цієї операції
2. Коли виробник має намір помістити об'єкт у буфер, а
буфер повний, він має чекати, поки в буфері звільниться
місце
3. Коли споживач має намір отримати об'єкт з буфера, а
буфер порожній, він має чекати, поки в буфері з'явиться
об'єкт
10. 10/19Лекція 6
Рішення задачі
виробник-споживач
1. Організуємо критичну секцію для роботи з
буфером. Для цього використаємо двійковий
семафор lock
2. Для організації очікування виробника
впровадимо семафор empty, значення якого
дорівнює кількості вільних місць у буфері
Виробник перед спробою додати об'єкт у буфер
зменшує цей семафор, а якщо той дорівнював 0 –
переходить у стан очікування
Споживач після того, як забере об'єкт з буфера,
збільшує цей семафор, при цьому, можливо,
ініціюється пробудження виробника
11. 11/19Лекція 6
Рішення задачі
виробник-споживач
3. Для організації очікування споживача
впровадимо семафор full, значення якого
дорівнює кількості зайнятих місць у буфері
Споживач перед спробою забрати об'єкт з буфера
зменшує цей семафор, а якщо той дорівнював 0 –
переходить у стан очікування
Виробник після того, як додасть об'єкт до буфера,
збільшує цей семафор, при цьому, можливо,
ініціюється пробудження споживача
12. 12/19Лекція 6
Псевдокод рішення задачі
виробник-споживач
semaphore lock = 1, empty = n, full = 0; // на початку буфер порожній
void producer() {
while(1) { // працює постійно
item = produce_new_item(); // створюємо об'єкт
P(empty); // перевіряємо наявність місця
P(lock); // входимо у критичну секцію
add_to_buffer(item); // додаємо об'єкт до буфера
V(lock); // виходимо з критичної секції
V(full); // повідомляємо про новий об'єкт
}
}
void consumer() {
while(1) { // працює постійно
P(full); // перевіряємо наявність об'єкта
P(lock); // входимо у критичну секцію
item = get_from_buffer(); // забираємо об'єкт з буфера
V(lock); // виходимо з критичної секції
V(empty); // повідомляємо про вільне місце
consume_new_item(item); // споживаємо об'єкт
}
}
13. 13/19Лекція 6
Проблема взаємних
блокувань
Припустимо, у функції “виробник” ми поміняли місцями P(empty) і
P(lock):
void producer() {
while(1) { // працює постійно
item = produce_new_item(); // створюємо об'єкт
P(lock); // входимо у критичну секцію
P(empty); // перевіряємо наявність місця
add_to_buffer(item); // додаємо об'єкт до буфера
V(lock); // виходимо з критичної секції
V(full); // повідомляємо про новий об'єкт
}
}
Перевірка умови з можливим очікуванням здійснюється всередині
критичної секції. Можлива така послідовність дій:
1. Виробник входить у критичну секцію, закриваючи семафор lock
2. Виробник перевіряє семафор empty і очікує на ньому (буфер повний)
3. Споживач намагається ввійти у критичну секцію і блокується на
семафорі lock
Така ситуація називається взаємне блокування або тупик
(deadlock)
14. 14/19Лекція 6
Типові причини виникнення
взаємних блокувань
Необережне застосування семафорів. Найчастіше –
через застосування семафору всередині критичної секції
див. приклад вище
Необхідність різним потокам одночасно захоплювати
кілька ресурсів
“Філософи, що обідають”
Реальна ситуація (різна послідовність захоплення ресурсів):
Потік А Потік В
1 Захопити диск 1 Захопити принтер
2 Захопити принтер 2 Захопити диск
3 Звільнити диск 3 Звільнити диск
4 Звільнити принтер 4 Звільнити принтер
А1А2В1 (В очікує)А3А4В1В2В3В4 – успішно
А1В1В2 (В очікує)А2 (А очікує) – взаємне блокування
15. 15/19Лекція 6
Шляхи вирішення проблеми
взаємних блокувань
Запобігання взаємних блокувань
1. Запит ресурсів здійснюється у певній послідовності,
спільній для усіх потоків
2. Якщо один з потрібних ресурсів зайнятий, то потік має
звільнити усі ресурси, що йому необхідні одночасно, і
повторити спробу через деякий час
3. Потік запитує усі ресурси у центрального диспетчера і
очікує їх виділення.
Розпізнання взаємних блокувань
Існують формальні методи, які вимагають ведення
таблиць розподілу ресурсів і запитів до них
Відновлення після взаємних блокувань
Аварійне завершення усіх або деяких заблокованих
потоків
“Відкіт” до контрольної точки
16. 16/19Лекція 6
Спеціалізовані засоби синхронізації
низького рівня – м’ютекс
М’ютекс (mutex – від mutual exclusion)
призначений для взаємного виключення
Має два стани: вільний і зайнятий
Визначені дві атомарні операції: зайняти і звільнити
На відміну від двійкового семафора, звільнити
м’ютекс може лише той потік, що його зайняв
(власник м’ютекса)
У деяких реалізаціях існує третя операція –
спробувати зайняти м’ютекс
Повторна спроба власника м’ютекса зайняти той
самий м’ютекс призводить до блокування
Існують рекурсивні м’ютекси, які діють за принципом
семафора лише для свого власника
17. 17/19Лекція 6
Спеціалізовані засоби синхронізації
низького рівня – умовна змінна
Умовна змінна призначена для очікування події
Умовна змінна пов'язана з певним м’ютексом і
даними, які він захищає
Визначені три операції:
сигналізація (signal) – потік, що виконав дії з даними у
критичній секції, перевіряє, чи не очікують на умовній
змінній інші потоки, і якщо очікують – переводить один з
них у стан готовності (потік буде поновлено після
звільнення м’ютексу)
широкомовна сигналізація (broadcast) – те ж, що й
сигналізація, але у стан готовності переводить усі потоки
очікування (wait) – викликається, коли потік у критичній
секції не може продовжувати роботу через невиконання
певної умови
• м’ютекс звільняють і інші потоки можуть мати доступ до даних
• після того, як інший потік здійснив виклик signal або broadcast,
потік знову повертається до виконання
• потік захоплює м’ютекс і продовжує роботу в критичній секції
Операція очікування не атомарна
18. 18/19Лекція 6
Особливості використання
умовних змінних
Перед викликом wait() необхідно перевіряти умову в
циклі while()
while(! condition_expr) // вираз для умови
wait(condition, mutex);
Умовні змінні використовуються лише всередині
критичних секцій, на відміну від семафорів,
використання яких всередині критичних секцій
призводить до блокування
Умовні змінні не зберігають стану, на відміну від
семафорів, які зберігають стан
Рекурсивні м’ютекси не можуть бути використані з
умовними змінними, оскільки рекурсивний м’ютекс
може не звільнитися разом із викликом wait()
(гарантоване взаємне блокування)
19. 19/19Лекція 6
Монітор
Монітор – це набір функцій, які використовують
один загальний м’ютекс і нуль або більше
умовних змінних для керування паралельним
доступом до спільно використовуваних даних
Правила реалізації монітора:
Під час входу в кожну функцію монітора слід займати
м’ютекс, під час виходу – звільняти
Під час роботи з умовною змінною необхідно завжди
вказувати відповідний м’ютекс (для роботи з умовною
змінною м’ютекс повинен завжди бути зайнятий)
Під час перевірки на виконання умови очікування
необхідно застосовувати цикл, а не умовний оператор