owned this note
owned this note
Published
Linked with GitHub
###### `operating Systems`
[TOC]
# Introduction (Operating Systems )
Current OS in use
- windows
- ubuntu
- linux
- MAC OS
- Android
OS is the program responsible for managing hardware device.
It acts as intermediary between User and computer hardware.

Systems software is used to directly command and modify the computer hardware
## Operating Systems (OS Structure)
Without an operation systems, application would need to communicate directly with the hardware,instruction it load itself into memory and specifying memory allocation requirement. It's very complex and intricate ..
Operation systems acts as intermediaries, simplifying those complex steps
Types of functions
- Provide the interface between user and hardware
- Allocated memory
- Management of the memory, security..
# Basic Of Operation Systems
## The Basic structure of Computer Systems
A Modern general-purpose computer consist of the CPU and hardware controller accessing sharing memory via common bus.

### Device Controller and memory controller
Each device controller manage a specific device
CPU and Device controller can execute concurrently
Memory Controller have to proper allocate memory for the device loading and execute.
## Bootstrap program
The bootstrap program is the initial programe loaded into the main-memory
It is stored in the ROM-Memory and responsible for locating the OS program
Initial the systems startup, and load the OS kernel into the main memory.
## Interrupt & systems call(Monitor Call)
### Interrupt
(Hardware interrupt)
When hardware need to interrupt some process, the device will send the signal through to common bus, instructing the CUP interrupt the current task.

### Systems Call
(Software interrupt)
IF the interrupt was triggered by software, we typically referred to as systems call or Monitor call
### The Response of interrupt or Systems call
When the cup receive the interrupt signal, it immediately transfer execution to a fixed location
- Fix location: usually the start address of interrupt server routine(ISR)
- Interrupt Service Routine perform something that the intercept want to do or it want to execute, Those are write in ==Serve Routine==
#### Flows char
1. CPU receives interrupt signal
2. Current process is stopped
3. Transfer to the start address of ISR
4. Execute ISR
5. Completion
6. CPU returns to the point of interruption
# Basic Of Store Structure
## Store Structure

### Hierarchy of Storage Device
- Register
- Cache
- Main-Memory
- Electronic Disk
- Magnetic Disk
- Optical Disk
- Magnetic Tapes

## Main Memory (Volatile) and Second Memory (Non-Volatile)
Main Memory is our Random Access Memory (RAM).
The function of main memory is to load the data for executing when performing operations
Secondary Memory is our secondary storage device.
Consider the scenario of double-clicking on a.txt:

## Volatile and Non-Volatile device
- Volatile Definition
Lost the contents, when the power is removed
- Non-Volatile Definition
Retain the contents, when the power is removed

- Special case
Non-Volatile -> NVRAM (It contains the battery backup)
# Basic Of I/O Structure

## I/O Structure
The significant portion of the OS code is dedicate to managing the I/O operations.
## Device Controller
Device Controller have two function to maintain the device working.
Maintain:
- Local Buffer Storage
- Set of special-purpose Register !!
Each device have a device driver for its Device controller.
## Device Drivers
As device vary , It's impossible for the OS program to know all device instruction for communicate.
Device Driver, according to the device controller, provide the uniform interface between the device and OS program.
Device Drive load the set of registers to the device controller.

## Working of I/O operation
Step:1
To start the I/P operation, the Device drive load appropriate register to device controller.

Step:2
The device controller, base on the register values, determine action to take
(I guess device controller content a micro processor to determine what action to take )
Step:3
The controller start transfer of date form device to its local buffer.

Step:4
Upon completing the data transfer, the device controller inform the device drive via interrupt signal that operation is complete.
Step:5
then the device drive return the controll to the operation systems


### Directory Memory Accessing (DMA
Using DMA can mitigate high costs
After setting pointers, buffers and counter for I/O device, the device controller can transfer an entire block of data directly from local buffer to memory without interacting with CUP.

Each block of data trigger one interrupt to notify the device drive that operations is completed !!!!

==In DMA, the CPU is not intervened!!==
# Computer Systems Architecture
Computer systems can be categorized based on the number of ==general purpose== processor
## Single Processor Systems
General Processor <---> CPU

A single processor system consists of one main CPU capable of executing a general instruction set, including instructions from user processes
Additionally, there may be a microprocessor used to perform specific tasks such as converting the keyboard inputs into binary code.
## Multiprocessor Systems

Multiprocessor systems as know as parallel systems or coupled systems, involve multiple general-purpose processor.
These processors closely communicate with each other, sharing common resources like buses, memory, and devices.
### Advantage

### Type of multiprocessor systems
#### Symmetric
In symmetric systems, those CPU are similar and participate equally in performed the test task Process-1,Process-2,Process-3

#### Asymmetric
In Asymmetric systems, the master slave approach is used.
One of the CUP acts as the master and monitoring and assign remain the task to slave processor
Slave processor take are of particular process.
Master -> Monitors and assigns tasks.
Slave 1 -> Process 1
Slave 2 -> Process 2
Slave 3 -> Process 3

## Clustered Systems

Clustered systems consist of two or more individual systems coupled together.
## Type of clustered systems
### Symmetric
Tow or more host run the application and monitor each other
### Asymmetric
Host standby host configuration, where the main host monitors other hosts, and the remaining hosts run applications.
# Operating Systems Structure
## Multiprograming
Multiprogramming design is keep the CPU busy and allowing switch between multiple jobs without waiting the I/O operation finish.
Considering the following illustration.

In the scenario, CPU doesn't wait the JOB-1 to finish I/O operation, instead it continue executing JOB-2 .....

## Time Sharing (Multitasking)
A time sharing systems enable many user to to share the computer simultaneously

the technique take advantage of the processor speed is much faster then the the human reaction time
- Each user has least one separated program in the memory
- A program load into memory and executed is referred to as a 'process'.
# Operating Systems Service
An operating system provides an environment for programs and users to execute.
## User interface
The User interface allow the user to interact with Operation Systems
e.g.
CLI Command line interface
GUI Graphic User Interface


## Programming Executing
OS can load the program into the memory and execute the program
Source Code ---> Compiler ---> Object Code ---> Executor ---> Output
## I/O operation
OS facilitates input and output operation for running programs controlling access to input/output device(Hardware).

## File Systems manipulation
File creation, modification, deletion, and searching are controlled by the operating system. OS also manages access restrictions.
## Communications
OS also provide the communication between process, whether process communication are on the same computer or network together.
## Error detection

Error detection is crucial for debugging purposes.
## Resource allocation
OS allocates resources such as CPU, files, I/O devices, and main memory to different processes and users.
Resource type
- CPU
- File
- I/O Device
- Main memory
## Accounting
Accounting -> Monitor
Accounting involves monitoring and tracking how much and what types of resources users are utilizing
## Protection and Security
### Process
When multiple processes are executing simultaneously, each process is prevented from interfering with others. The OS ensures that access to system resources is controlled for all processes.
# User Operation Systems Interface
## Command interpreter
In some operations systems command interpreter is include in kernel.
But some operations tread the Command interpreter as the program.
- CMD in Windows
- Terminal in Linux
One Operation systems typically have multiple command interpreter, know as 'shells'
e.g.
- Bourne shell
- Bash Shell
- C shell
Two approaches for executing binary or task.
- First Approach
1. The command interpreter contains the code to perform a specific task.
- Second Approach
The command interpreter doesn't contain the code for tasks
. instead, it calls a program or binary based on the entered command.
# Systems Calls
Systems calls providing programmatic way to request a services form the kernel of operation systems (resource)
These calls are typically implemented as a routine written in C or C++.
## User Mode
In user mode, programs can execute but are not allowed to directly access or modify hardware or memory.
## Kernel Mode
Kernel mode is a privilege mode that allows processes to directly access memory and hardware

## Context Switching
When a user switches from user mode to kernel mode, it is known as context switching.
## Example of Systems Called


# Type of systems called
Systems called can be grouped 5 categories
## Process Control
### Create, End, Abort
Create, terminal or abort process
### Load, Execution
Load and execute a program
### Get process attribute, set process attribute
Retrieve or modify process attributes.
### wait for time, wait for event,signal
Pause process for specified time wait for an event, or signal an event.
- allocate memory, free memory
## File Manipulation
- Create, Delete, Open, Close
- Read, Write, Reposition file
- Get file Attributes, Set file attributes
## Device Manipulation
- Request device, Release device
- Read, write, Reposition device
- Get device attribute, Set device attributes
- logically attach, detach device
## Information Manipulation
- get time or date, set time or date
- get systems data, set systems data
- get process, file, device attributes
- set process, file, device attributes
## Communication
- create or delete communication connection
- send, receive the message
- transfer status information
- Attach or Detach the remove device
# System Program

Systems programs can be grouped base on the kind of the task they perform
## File Management
- Create
- Delete
- Copy
- Rename
- Print
- Dump -> Display the content of file in hex form
- List -> Display content of a directory
## Status information
Asking Systems for:
- Data, Time
- Disk space
- The number of user
- Detail performance
- Debugging or login information
## File Modification

## Programming Language support
These system programs support programming languages like C, C++, and Python:
- compiler
- assembler
- debugger
- interpreter
## Programming loading and execute
After compiling or assembling program, the next step is loading it to memory and executing it.
There are systems program can help us to do that.
- Absolute Loader
- loads a program into memory without modification
- Relocated Loader
- Adjust the program address's space during loading
- Linkage editor
- Combine multiple object program into a single execution.
- Overlay Loader
- Allow the program to be large than the machine's physical memory space.
- Debugging
## Communication
Systems program provide the machine for
- Create the virtual connection among the process, user, operation systems
- Allow the user send the message to another screen.
- Transfer the file to another machine
- Browsing the web page.
# Operation systems design & implementation
## Design goal
Designing an operating system involves defining goals and specifications. Considerations include the choice of hardware, the type of system, and user requirements.
User goal

Develop goal

## Mechanism and Policy
Mechanism determine how to do something
Policy determine what should be done
It's essential to separate the machine mechanism and policy

In resource allocation, for example
The mechanism is how the resource was allocated, while the policy is when system decide the assign or deny resource
## Implementation
Once the operating system design is complete, the next step is implementation.
Traditional operating systems were implemented in assembly language, while modern operating systems are implemented in high-level languages like C/C++.
Advantage

# Structure of Operation Systems
## Simple Structure
MS-DOS (Intel-8088 Assembler)
Application
Systems program
Device Drive
ROM BIOS - (Device Drive)

In the structure, the application can access the hardware directory without going through the system program and device driver.
Prone to malware and crash:if an application crashes, the entire system may crash.
## Monolithic Structure
Example: Earlier Unix Operation Systems
Monolithic structure is also a simple structure
- Application
- Command and shell
- Compiler and interpreter
- Systems library
- Systems-call (interface)
- Kernel functionalities (I/O function, file systems, CPU scheduling, signal terminal, etc.)
- Kernel interface to hardware
- Hardware controllers (memory controller, keyboard controller, etc.)

## Layered Structure
In layered structure
Each layer can only use the services provided by the next lower layer.

## Microkernels
Micro kernel only contain the core functions. part of systems program is moved to the user mode.
Microkernel responsible of communication of client program and system program
Disadvantage:
Having performance overhead due to message passing.

## Module (Current os using structure!!)
Current bast design for operation systems
Mixes layered structure and microkernel methods
Involve the object oriented program to create modular kernel

No message passing; objects dynamically load in the core kernel.
# Virtual Machine
Virtual Machine is know as VM
VM isolates harware resource from each other
The fundamental concept is to abstract hardware(CPU, Network adapter, memory ) into different execution environments.

VM1 Assigned hardware resources from physical hardware.
## VM implementation
VM software runs in physical Kernel mode, and the VM itself runs in physical User mode.
## Virtual machine User mode and kernel mode
The VM has its own user mode and kernel mode, known as 'virtual user mode' and 'virtual kernel mode.' Both run in the physical user mode.

# Operation system generation and systems boot
Operation systems are designed to run on a class of machine
However, Different machine have different hardware and peripheral devices.
## Operation System Generation
SYSGEN is first program when starting computer.
In ensure es the the OS compatible and work for various machine
SYSGEN process have to gather information about
- What CPU is used
- How much memory are available
- What device are available
- what OS option are desired (computer systems)
SYSGEN uses this information to generate the operating system.
## Systems boot
The procedure of starting a computer by ==loading the kernel into the memory== is know as systems boot
### Bootstrap program & Bootstrap loader
Computer hardware didn't know the location of Kernel, A bootstrap program locates the kernel and load it into the memory to complete the systems boot.
This process we called "booting"
Bootstrap program and bootstrap loader are typically stored in ROM memory since RAM is unknown at system startup.
(ROM always not be erase!! and it is )
## Firm/ROM
Firmware is read-only, typically used in small or mobile devices. Bootstrap program and loader can be stored in firmware.
### Boot State → Running State
Once the bootstrap program is loaded, it traverses the file system to find the kernel, loads it into RAM, and executes it, transitioning from the boot state to the running state.
# Process Management(Process and threads) - Chapter 3 Process
Processes and threads are different entities
## Process
A Program is write by high level language, and computer only understand binary code.
The program have to be converted into binary code.
When binary code is loaded and executed in memory that execution is know as `Process`
In some case, Single program can be associated with multiple process such in the case of chrome.exe

## Threads
A Thread is unit of execution with a process
One process can have one thread or many threads.
Process explorer allow use to see threads in process

## Difference between process and threads

# Process State
As process executes, It may be one of the following state
## New state
The process is created !
## Running state
Instruction was executed
## Waiting state
Wait for some event such as I/O operation or reception signal
## Ready state
The process waiting to be assign resource to a process
## Terminated State
The process has finished process
## Diagram of process state

# Process Control BLock
Diagram of PCB & Process

## Process ID
Process ID in PCB use to identify specify process

## Process status
Process status
- NEW
- Ready
- Running
- Waiting
- Terminal

Process state represent a the current status of a particular process.
## Program counter
When the process is execute, the line of instruction or code are execution line by line.
Program counter indicate the address of next instruction.

## CPU Register
There are many kinds of register in PCB
- Index Register
- Stock Pointer
- General Purpose Register

CPU register will tell use what the particular register that are be used by particular process.
## CPU scheduling information
CPU scheduling information have the priority of process
Have the pointer to scheduling queue.

## Memory Management information

## Accounting information
Record the different resource used in process such as UPC, time, memory
## I/O status information
I/O PCB will assign the I/O device to a particular process.

# Process Scheduling
## Objective of multiprogramming and time-sharing
The object of Multi-programming have process run all the time in the memory to archive the max CPU usage of utilization
Time sharing mean the CPU can very fast switch CPU in process to archive no delay with user When user do multi task in some time
In fact when the computer play the audio , running game, transfer data, they no running is same time, that just rely the mechanism of time sharing and muli-programming
## Process Scheduling
Processor Scheduling select an process(possible from a set of several ) and assign it to CUP for execution
### In single-processor Systems
There will be Only one process running at time
IF there are more process, the rest of processes have to wait until the CUP is free
So process Scheduler take care for the rest of processes
## Scheduling Queue
### Job Queue
As process enter the systems, they are input the Job queue which consists of all process in systems
### Ready Queue
Once the process enter the ready statement and wait for CUP execute instruction or code, the process will enter the read Queue and wait for being assign to CUP.

# Context Switch
Interrupts occur the operation systems to change a CPU from process current task and to run the kernel routine.
Context switch operation happen frequently on general-purpose systems.
Context switch mean when CUP store current state and restore state is know as context switch.

For instance, When the systems interrupt occur the systems have to save the current context, and execute interrupt routine.
# Operation on Process
## Process Creation
### Creation of Process
During execution, process can use systems calls to create sub-process running under the parent process
### Process Tree
Each created process forms a tree structure with the parent process


### Behavior of parent and child process in terms of execution.
Case:1
When a child process is created and executed, it may occupy the part of resources from the parent process and concurrently with the parent process until the child process is terminated.
Case: 2
It may occupy all of resource from the parent process, and parent process have to wait until the child process was terminated
### The behavior of child process term of the address space
Case 1: The child process duplicate the address space of the parent process, consisting of both data or code
Case 2: the child process is seen as a new program and loads into the address space of the parent process.
## Process Termination
### Termination of Process
##### Process Termination Flow
Situation 1: Process finished final statement
- When Process finishes its final statement,the operations systems will using exit() system call to terminate it.
- Upon termination by the systems call,the process return a status value (integer) to parent process. (via the wait() system call)
- All the resource allocated to terminated process are release.
Situation 2: Process be terminate by another process
- Only the parent process can terminate the the child process by invoking system call.
- User have ability to arbitrary terminal process.
### Reason way the parent process may terminate its child process
Reason 1
- The Child process has exceeded the allocated usage of some the resource.
Reason 2
- The Task performed by the child process is no longer required, leading to terminate by parent process.
Reason 3
- If the parent process is terminated, the child will be terminated simultaneously.
# Interprocess Communication (IPC)
## Independent process and cooperating process
Independent process that can't affect or be affect by the other process executing in the systems
Cooperation Process that can affect or be affected by other processes executing in the systems.
## Reason for providing an environment that allow process cooperation.
- Information Sharing
- Computing Speedup
- Module programming
- Convenience
## Model of Interproess Communication(IPC)
Cooperating process require an interprocess communication (IPC) mechanism.
### Shared Memory
In the share memory model, a region of share memory is established for cooperating process, and process can exchange the information by reading or wiring data in the shared region.
### Message passing
In the message passing model, communication takes place by means of message exchange between cooperating processes.
## Diagram of Share Memory and Message Passing

# Shared Memory Systems (Single Systems)
In single systems, the communication of cooperating process is easy to implement by share-memory mechanism
In shared Memory mechanism, it required the communicating process to establish a region of share memory.
- Typically, a shared-memory region reside in the address space of the process (Shared memory segment)
- Other process want to access the shared Memory it have to attach it to their address space.

---
The operating system doesn't allow processes to directly access another process's memory by default.

Share memory region require two or more procession to agree to remove this restriction
## Producer-Consumer problem
A Producer process produce information that is consumed by a consumer process.
For Example:
- Compiler produce assembly code (Producer) which is consumed by assembler.
- The assembler produce the object module which is consumed by loader.
One of solution is shared memory.
The buffer will reside in the share memory region
The buffer can be filed by producer and emptied by consumer.
product and consumer process must be synchronized !, to prevent the consumer from consuming the item that has not yet been product.
## Type of Buffer

### Unbounded Buffer
Unbounded Buffer is unlimited size buffer
### Bounded Buffer
Bounded Buffer is fixed size buffer
# Message Passing Systems (Distribute Systems)
Message Passing mechanism allow process communicate in distribute systems, for instance remote hosts and networks
## Message send/Receive operations

## Fixed and Variable Size Message

## Methods to Establish a Logical Link Between Communicating Processes
If p and q process want to communicate with each other through the network. they need a communicated link between them

There are several methods for logically implement a link and send()/receive() operations.
- Direct or indirect communication
- Synchronous or Asynchronous communication
- Automatic and explicit buffer
There are several issues relate with feature like:
- Naming (Direct or Indirect)
- Synchronization (Synchronous or Asynchronous)
- Buffering (Buffer)
## Direct or Indirect communication
In director or indirect communication process have to refer and specify the name is called naming.
### Direct communication with Naming
##### Scenario: Direct Communication

Send Operation : (p, messageA)
Receive Operation(q, messageB)
Between each pair of process, there exists only one link
(Symmetry Addressing)
Send and Receiver process have to name the other for communication.
---
##### Scenario: Variant of Direct communication

- Send Operation : (p, messageA)
- Receive Operation(id, messageB)
- Receive a message from any process !!
ID is a variable it can be name of any process
This naming way is known as "asymmetry in addressing."
Sender (explicit name) <--Asymmetry--> Receiver (no explicit name)
### Indirect communication

Message are send and receive from mailbox.
The operation of Process P
- Send Operation: (mailbox ,message)
- Receive Operation: (mailbox, message)
Communication Property

Suppose have process p1,p2 and p3 all share mailboxA

P1 send the massage to Mailbox, while p2 and p3 execute receive operation from Malibox
The problems is which process will receive the message sent by p1 ?
The answer depend on which of the following method we choose

A mailbox may be owned by a process or by the operation systems
## Synchronous and Asynchronous Communication
Communication between two process using send() / receive() permit
There are different design of implement the permit
Permit type
- Blocking -> Synchronous
- Non-Blocking -> Asynchronous
## Blocking Send and non-BLocking send primitive
Blocking send
- The sending process is blocked until the message is receive the message from the mailbox
Non-Blocking send
- The sending process send the message and resume the operations
## Blocking received and non-Blocking Received primitive
Block receive
- The receiver block until the message is available
Non-blocking receive
- The receiver receive either a valid or a null.
## Buffering
When the process exchange the message in direct or indirect communication, the temporary queue can be implemented three way.
Zero Capacity, Bounded Capacity and Unbounded Capacity
### Zero Capacity
Zero Capacity -> the max length of queue is zero, thus the link cannot have any message waiting in it
### Bounded Capacity
Bounded capacity is finite queue, if the queue is full, the sender mush block until the space is available in queue.
### Unbounded Capacity buffer
The query length is potentially infinite, so any message can wait in it, the sender will never be blocked
# Socket in Operation Systems
Sockets are used for communication in Client-Server model
A pair of process communicate over the network employ a pair of sockets - one for each process
Definition: A socket is a endpoint for communication.
Socket Identification
IP:port
IP -> to Identify the machine
Port -> to Identify the process or service
Server will listen and wait until the receive the request from client. Once done, we can say the connect is complete.
Socket can implement most remote service such as telnet, FTP, HTTP ....
Note: Below 1024 port is use for stander service

# Remote Procedure Calls (RPC)
RPC is kind of client/server module
## Overview of how the RPC
IPC mechanism -> Local communication
RPC mechanism -> Remote Communication
RPC used in when the cooperating process reside on different systems over the network.
PRC is a protocol, it allow user request a service from a process located in another systems on the network without understand the network detail.

RPC use message base to passing the message to provide the remote service
Data of packet(Message)+ IP/TCP header
RPC daemon is a program reside on the remote service and listen the incoming request
Each message(Function, Message) send via RPC have to contain the identifier


The function is then was called and executed as request, and return the result to client in separate message.
## Invoke a procedure on remote host as it would invoke a procedure locally
Client
When client want to call the remote procedure(function), the RPC will call the stub, and stub will marshals the parameter(wrap the passing parameter) and located the server's PRC port for passing the parameters.
>The term Marshal refers to Network encapsulation.
Due to the stub in client, It allow us not to handle the Network encapsulation by our self and stub will automatically add the identifier
Once the server employs a similar stub to receive messages from the client, it will invoke the required function, it will invoke the required function, passing the parameters and returning the result in separate message.
# RPC Issue and Resolved
## Different data presentation in communication
For example:
Big-endian systems use high memory address to store the most significant byte, while the little-endian store the lasted significant byte at high memory address

Big -> High (Big-endian)
Big -> Low (Little-endian)
### Resolution-XRD Resolved
RPC system defied a machine-independent representation of data
One of represent is external data representation.

## Duplicate RPC Request
Due to the network unstable, Server possible process same RPC more then once
To solve the issue, we can use acknowledgment to tell the client request is received and executed.
THis acknowledgment mechanism is a kid of implementation of exactly once functionality
## RPC didn't know associated port (call Process)
Due to no share memory, RPC client only know the name of procedure. They didn't know the target port and IP

Resolution
## Resolution-rendezvous Mechanism
Rendezvous -> Matchmaker
Clint process sand the message contain the name of the RPC to the Matchmaker
Matchmaker will send the request to target server and return the specific process ip and port number

## The execution of Remote Procedure Call(RPC)

# Threads
Team -> Process
Team member -> Threads
Thread is a basic unite of CPU utilized
Thread contains thread ID,program counter, register set, Stock
## Shared data mechanism (threads to threads on same process)
code section
data section
other operation-systems resource
e.g. open the file or signal
## Single-thread process
Single-thread process is know as traditional/ heavyweight process

## Multi-thread process

Code , data and file section are share by three threads
For example

## Benefit of Multi-thread
### Responsiveness
Multi-threading allow the program continue running even if the part of it's block
### Resource Sharing
Sharing the code , data , other operations systems resource allow an process to have several different thread of activity within same address space
### Economy
Allocating memory and resource for procession is costly.
If we didn't use multi-thread, we need to create many process for performing different tasks.
### Utilization of multiprocessor architecture
A single thread can only run on one CPU, no mater how many are available.

Multi-threading can run on multi-CPU machine to increase concurrency.

# Multi-threading & Hyper threading
Types of threads
User threads
User thread is created and managed by the user or developer
Kernel threads
Kernel threads is created and managed by the operations systems(directly)
User thread and kernel thread have a relationship for archiving the task.
## Multi-threading Model
### Many to One Model
Multiple user threads map to single kernel threading
One process haves 3 user threads and 1 kernel threads

Limitation:
1. The entire process will block if a thread makes a blocking systems call
2. One processor only can process one kennel thread at a time, so multiple user thread are unable to run simultaneously on multiprocessor.
3.
### One to One model
One to One model allow multiple user thread to run concurrently
and the entitle process not easily be block if the one user thread make a blocking a systems call
One process haves 3 user threads and 3 kernel threads

Limitation
It will generate to great overhead in entity systems if One process create to many kernel threads, the reason is the computer's processor is limit.
### Many to Many Model(Best Model )
The issue of One to one and manay to one model can be solved in Many to Many model


## Hyperthreading
Hyper threading is also called simultaneous Multithreading
Simultaneous Multithreads mean that we are having more then one multi-threading going on at same time
### Work
Hyperthreaing systems allow their processor core's resource become multiple logic processor for performance.

Check the number of physical processor and logical processor windows management instrumentation console.
```
C:\Users\Meowhecker>wmic
wmic:root\cli>CPU Get NumberOfCores
NumberOfCores
6
wmic:root\cli>CPU Get NumberOfCores,NumberOFLogicalProcessors
NumberOfCores NumberOfLogicalProcessors
6 12
```

# Fork() and Exec() System call
Fork() and Exec system call are mainly use in Linux Systems,
## Fork() systems call
Fork systems call is used to create a duplicate the process
New duplicated process is called child process that are same with parent process, beside the PID is different
Fork1.c
```c
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(){
fork();
printf("meowhecker PID = %ld \n", getpid());
return 0;
}
```
OutPut
```
┌──(kali㉿kali)-[~/Desktop/OperationSystems]
└─$ ./fork1
meowhecker PID = 176831
meowhecker PID = 176832
```

Fork2.c
```c
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(){
fork();
fork();
printf("meowhecker PID = %ld \n", getpid());
return 0;
}
```
Output
```
┌──(kali㉿kali)-[~/Desktop/OperationSystems]
└─$ ./fork2
meowhecker PID = 177691
meowhecker PID = 177693
meowhecker PID = 177692
meowhecker PID = 177694
```

Case Fork 3

## Exec() systems call
when Exec() systems call is invoke, it will replace all process content(include all threads) via the parameter that was passed in exec function
Due the just only replace the contain the PID didn't be changed. w
Exec1
```c
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(int argc,char* argv[]){
printf("exec1.exe PID=%d \n",getpid());
char* args[] = {"meowhecker",NULL}; //Null -> list of end (necessary)
execv("./exec2",args); //replace process
printf("exec1 Now!!!");
return 0;
}
```
Exec2
```c
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(int argc,char* argv[]){
printf("exec2.exe PID=%d \n",getpid());
printf("exec2 Run Sucess!!");
return 0;
}
```
Output
```
┌──(kali㉿kali)-[~/Desktop/OperationSystems/exec]
└─$ ./exec1
exec1.exe PID=196075
exec2.exe PID=196075
exec2 Run Sucess!!
```
# Threading Issue
## (exec() & fork())
Fork issue
If one threads in process call the fork() systems call, does the process duplicate the all threads or is the new process single thread.
Solution:
Unix have two version of fork(), one is duplicated all threads and another is duplicate only the thread that called the fork() system call.
wather
## Which version of fork() to use and when
The answer is depended on whether the exec systems call be invoked after the fork()
### If Exec() is invoked immediately after forking
We only need to duplicate one thread that call the fork(),
and the exec will replace the all contain with the threads

### If the separate process does not call exec after forking
the separate process should duplicate all threads.
## Thread Cancellation
Thread cancellation is the task of thread terminating before it has completed!!.
Cases
Multithreads search specific value or load the web browser.

A threads is to be cancel, we called it target threads.
## Cancellation of the target threads
### Asynchronous Cancellation
Asynchronous Cancellation mean the target thread is allow be intermediately terminated by the other thread without any permission
It will generate many issue
- Data Sharing issue
Threads typically will use the share region

- Resource Allocate issue
Asynchronous Cancellation may not free a necessary systems-wide resource.
### Deferred Cancellation (Better methods)
Deferred Cancellation only occur whent the target thread check the flag to determine if it should be terminate
(Cancelt safetly)
### Deferred Cancellation
# CPU Scheduling(SKIP)
# Ch-6
# Process Synchronization
## Cooperating Process
Cooperation Process is one that can affect or be affect by other process
Cooperation process can share the data and code via logical Address space and data can be only is file or message
Issues:
In Muliple process systems, concurrent acess the share memory may result in data inconsistency !
## Share Memory Systems and Procedure-Consumer Problems.
int counter = 0

### Counter++ in machine code
Register1 = Counter
Register1 = Register1 + 1
Counter = Register1
### Counter-\- in machine code
Register2 = Counter
Register2 = Register2 + 1
Counter = Register2
## Race condition
Execute Counter++ and Counter-\- concurrently

Error (Race Condition)--> Multiple Process use share region(counter) is same time
TO avoid processes not to interfere with each other, we need to process synchronization.
# Critical Section
Each process have a segment of call called critical section (change variable, update the table, write the file)

But the mechanism will affect the process cooperate with other process.
We have to thing way to solve the issue.
## Entry, Exit, Remainder Section
1. Each process must request permission to enter the critical section.
2. The section of code implementing this request is the entry section
3. The critical section my be following by exit section
4. The remain code is the remainder section
General Structure of typical process

## A solution to the critical-section must satisfy the following three requirements
### Mutual Exclusion
Only one process can access or write data to critical section at a time.
### Progress
If no processes access the critical section, some process wish to access the critical section, then only the process no execute in their remainder section can access it.
if a process is not using the critical section, then it should not stop any other process from accessing it.
### Bounded Waiting
Bounded waiting means that each process must have a limited waiting time
# Peterson's solution
侯智晟
meowheckerouo@gmail.com