system programming: os conceptsmmlab.uos.ac.kr/system programming/pdf/osconcepts2014... ·...
TRANSCRIPT
Copyright, 2012 © Multimedia Lab.,
System Programming: OS Concepts
Process, Thread, Kernel Object
Seong Jong Choi [email protected] Multimedia Lab. Dept. of Electrical and Computer Eng. University of Seoul Seoul, Korea
Instruction Cycle
9/3/14 UCB CS162 Fa14 L2 2
PC:
Registers
ALU
1.Instruction fetch
2. Decode
3. Execute
Memory
instruction
next
decode
data
Processor
OS란?
• 효율성과 편의성을 위해 제작된 소프트웨어
• 효율성(Efficiency)
– 하드웨어 자원을 효율적으로 관리
– 사용자 간의 보안(Protection) 유지
– 오류 관리
• 편의성(Convenience)
– 사용자가 하드웨어 자원을 편리하게 사용
– Standard Library, GUI
2014-10-15 System Programming 3
OS란?
• 대부분 다음 제목을 다룬다. – Process Management
• Multitasking/multiprogramming?
• CPU Scheduling
• Synchronization / Mutual exclusion primitives
• Communications? (Does Email belong in OS?)
– Memory Management
– I/O Management
• OS라고 주장할 수 있는 제목들 – File System?
– Multimedia Support?
– User Interface?
– Internet Browser?
2014-10-15 System Programming 4
OS란? (계속)
• 일반적인 OS의 정의는 없다.
• OS를 사면 설치될 수 있는 모든 것?
– But varies wildly
• 컴퓨터에서 항상 돌아가고 있는 프로그램을
“Kernel”이라 한다.
– 이외는 시스템 프로그램(컴파일러, 라이브러리) 또는 응용
프로그램이다.
2014-10-15 System Programming 5
OS란(계속)
• Operating systems provide a virtual machine abstraction to handle diverse hardware – Software emulation of an abstract machine
– Give programs illusion they own the machine
– Make it look like hardware has features you want (e.g. Virtual Memory, File system, Network system etc…)
Virtual Memory: limited physical memory -> Full virtual memory
File System: Hard disk -> Files, Folders, Subfolders
Network system: network card -> pipe to other computers
• Two Types of VM – System VM
– Process VM
2014-10-15 System Programming 6
System VM
2014-10-15 System Programming 7
OS의 진화
• 컴퓨터 진화의 3단계
– 비싼 HW, 싼 임금: Eniac
– 싼 HW, 비싼 임금: PC
– 아주 싼 HW, 아주 비싼 임금: SmartPhone, Network
2014-10-15 System Programming 8
OS 고고학
• 처음부터 개발한 OS가 매우 드물다. 대부분 계보를 가지고 있다. • Multics AT&T Unix BSD Unix Ultrix, SunOS, NetBSD,…
• Mach (micro-kernel) + BSD NextStep XNU Apple OSX, iphone iOS
• Linux Android OS
• CP/M QDOS MS-DOS Windows 3.1 NT 95 98 2000 XP Vista 7 8 phone …
• Linux RedHat, Ubuntu, Fedora, Debian, Suse,…
2014-10-15 System Programming 9
Uniprogramming vs Multiprogramming vs Multitasking
• Uniprogramming: – 프로그램이 한번 시작되면 도중에 중단 없이 끝날 때까지 돌아간다.
– MS/DOS
• Multiprogramming: – 한 프로그램이 I/O를 기다리면 다른 프로그램이 수행된다.
• Multitasking (or Time-Sharing) – 시간을 나누어 여러 프로그램을 차례로 돌린다.
2014-10-15 System Programming 10
Time-Sharing
• Throughput vs Response time
• 직원1명, 손님3명
• 성능과 관련된 2가지 평가지표
– Throughput:
어떻게 하면 직원이 많은 손님을 서비스할 수 있을까?
– Response Time:
어떻게 하면 손님이 기다리는 시간을 줄일 수 있을까?
2014-10-15 System Programming 11
Multiprograming의 문제
• 문제1: VM:
– 모든 프로그램이 각자의 기계를 요구함
• 문제2: Concurrency & Protection:
– 동시성: 여러 개의 프로그램이 자원을 공유.
– 보호: 허락하지 않은 상호 접근 불가
• 문제3:
– 프로그램 간의 협력/통신
2014-10-15 System Programming 12
Main Topic
• Multiprogramming
• Process
• Threads
• Address spaces
2014-10-15 System Programming 13
A컴퓨터에서 B컴퓨터로 프로그램 계속 실행하기
• 가정 – A, B컴퓨터의 부품은 같은 사양의 부품으로 구성된다.
– 하드디스크는 하나
– 예, CPU, Main board, I/O, OS
– A컴퓨터는 현재 하나의 프로그램만 수행되고 있다.
– A 컴퓨터에서 특정 주소의 기계어까지 수행하고 다음 기계어부터는 B 컴퓨터 실행해야 한다.
– 컴퓨터를 옮기기 전, A 컴퓨터 HDD에 필요한 최소한의 정보만 저장할 수 있다. 이 정보는 B 컴퓨터에서 프로그램이 계속 실행되기 전에 사용될 수 있다.
• 문제 – A 컴퓨터 HDD에 저장해야 할 정보는?
2014-10-15 System Programming 14
프로그램을 수행하기 위해 OS가 수행하는 작업
9/3/14 UCB CS162 Fa14 L2 15
int main() { … ; }
edito
r
com
pile
foo.c Foo.exe Lo
ad &
Ex
ecut
e
0x000…
0xFFF…
data
instructions
data
heap
stack
Memory
CPU registers
PC:
OS
기계어프로그램 C 프로그램
프로세스
프로그램에서 프로세스로 • 기계어프로그램 파일을 메모리로 이동 • Stack/Heap 영역 생성 • Instruction 수행 • System Service제공 (관련 정보 관리) • OS 및 프로세스 보호 (관련 정보 관리)
instructions
Dual Mode Operation • What is needed in the hardware to support “dual
mode” operation? • a bit of state (user/system mode bit) • Certain operations / actions only permitted in
system/kernel mode – In user mode they fail or trap
• User->Kernel transition sets system mode AND saves the user PC
– Operating system code carefully puts aside user state then performs the necessary operations
• Kernel->User transition clears system mode AND restores appropriate user PC
– return-from-interrupt
9/3/14 UCB CS162 Fa14 L2 16
Key OS Concept: Address Space • Program operates in an address space that is
distinct from the physical memory space of the machine
9/3/14 UCB CS162 Fa14 L2 17
Processor Memory
0x000…
0xFFF…
translator
A simple address translation: B&B
• Can the pgm touch OS? • Can it touch other pgms?
9/3/14 UCB CS162 Fa14 L2 18
code
Static Data
heap
stack
code
Static Data
heap
stack
code
Static Data
heap
stack
0000…
FFFF…
1000…
0000…
Program address
Base Address
Bound <
1000…
1100… 0100…
3.19 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
instructions
data
heap
stack
Memory
CPU registers
PC:
OS
프로세스
Process를 위한 자원 레지스터
사용자 메모리 자원
Instruction: 기계어 “text section”으로 불리운다. (혼동됨)
Data section static 변수를 위한 저장 장소
Heap 프로그램 수행 중 동적 할당
(Dynamic allocation: malloc())을 위한 저장 장소 Stack
매개 변수, 지역변수, return 주소를 위한 저장 장소 Registers:
현재 프로그램 진행 상황이 저장됨 program counter (PC)
커널 메모리 자원
IO File Descriptor, Kernel Objects
A Thread 실행의 단위: Context-switching (CPU Scheduling)의 기본 단위
3.20 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
프로그램 vs. 프로세스
하나의 프로그램(실행파일)으로 여러 개의 서로 다른 프로세스를 동시에 생성할 수 있다. 메모장 (notepad.exe)으로 my.txt을 열고 (Process #1), 메모장으로
your.text(Process #2)를 열 수 있다.
하나의 프로그램으로 하나의 프로세스로 실행하는 도중에 여러 개의 자식 프로세스를 생성할 수 있다. Chrome 새 탭을 열면 새로운 프로세스가 생성된다.
3.21 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Process란?
Process의 정의: “unit of resource allocation and execution” Owns memory (address space) Owns file descriptors, file system context, … Encapsulate one or more threads sharing process resources
Why processes?
Tradeoff between protection and efficiency Protection: 프로세스는 memory protection을 제공한다. 쓰레드는 특별한
mechanism을 사용하여 메모리를 보호한다. (매우 복잡) Efficiency: 쓰레드가 프로세스보다 효율적이다. (Context switching, 메모리 공유)
Application instance consists of one or more processes
2014-10-15 System Programming 21
3.22 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Process Control Block
How do we Multiplex Processes? 현재 프로세스와 관련된 모든 정보는 process control
block (PCB)구조체로 저장된다.
여러 프로세스에게 CPU 시간을 할당한다. (CPU Scheduling): Only one process “running” at a time Give more time to important processes
현재 사용하는 자원을 여러 프로세스와 공유한다.
(Protection): CPU를 제외한 모든 자원 공유 시 이를 제어한다.
3.23 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Process Control Block (PCB)
Information associated with each process Process state – running, waiting, etc Program counter – location of
instruction to next execute CPU registers – contents of all process-
centric registers CPU scheduling information- priorities,
scheduling queue pointers Memory-management information –
memory allocated to the process Accounting information – CPU used,
clock time elapsed since start, time limits
I/O status information – I/O devices allocated to process, list of open files
3.24 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
CPU Switch From Process to Process
This is also called a “context switch” Code executed in kernel above is overhead
Overhead sets minimum practical switching time Less overhead with SMT/Hyperthreading, but… contention for resources
instead
3.25 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Process State
프로세스 하나는 하나의 쓰레드만 존재한다고 가정
As a process executes, it changes state new: 방금 생성된 상태 running: 프로세스의 기계어가 CPU에서 실행 중인 상태 waiting: 프로세스가 특정 event 발생을 기다리는 상태 ready: 프로세스가 CPU 실행을 기다리는 상태 terminated: The process has finished execution
3.26 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Multiprocess Architecture – Chrome Browser
Many web browsers ran as single process (some still do) If one web site causes trouble, entire browser can hang or crash
Google Chrome Browser is multiprocess with 3 different types of processes: Browser process manages user interface, disk and network I/O Renderer process renders web pages, deals with HTML,
Javascript. A new renderer created for each website opened Runs in sandbox restricting disk and network I/O, minimizing
effect of security exploits Plug-in process for each type of plug-in
3.27 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Threads
So far, process has a single thread of execution Consider having multiple program counters per process
Multiple locations can execute at once Multiple threads of control -> threads
Must then have storage for thread details, multiple program counters in PCB
3.28 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Single and Multithreaded Processes
프로세스의 Heap은 여러 쓰레드가 공유함
3.29 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
쓰레드의 장점
응답시간 – 오랜 수행시간이 소요되는 일이 끝나지 않아도, 사용자의 입력을 받을 수 있다. 사용자 인터페이스에서 매우 중요한 요소이다.
자원 공유: 여러 쓰레드가 자원을 공유할 경우 (프로세스의 경우보다) 빠르게 접근할 수 있다.
경제성: 새로운 쓰레드를 생성하는 것이 새로운 프로세스를 생성하는 것 보다 경제적(적은 자원으로 가능하다)이다. 쓰레드 context-switching이 프로세스 switching 보다 빠르다.
확장성 (scalabity): multiprocessor 구조의 잇점을 사용할 수 있다.
Lec 3.30 9/11/13 Anthony D. Joseph and John Canny CS162 ©UCB Fall 2013
Putting it together: Process
Memory
I/O State (e.g., file, socket contexts)
CPU state (PC, SP, registers..)
Sequential stream of instructions
A(int tmp) { if (tmp<2) B(); printf(tmp); } B() { C(); } C() { A(2); } A(1); …
(Unix) Process
Resources Stack
Stored in OS
Lec 3.31 9/11/13 Anthony D. Joseph and John Canny CS162 ©UCB Fall 2013
Putting it together: Processes
…
Process 1 Process 2 Process N
CPU sched.
OS
CPU (1 core)
1 process at a time
CPU state
IO state
Mem.
CPU state
IO state
Mem.
CPU state
IO state
Mem.
• Switch overhead: high – CPU state: low – Memory/IO state: high
• Process creation: high • Protection
– CPU: yes – Memory/IO: yes
• Sharing overhead: high (involves at least a context switch)
Lec 3.32 9/11/13 Anthony D. Joseph and John Canny CS162 ©UCB Fall 2013
Putting it together: Threads Process 1
CPU sched.
OS
CPU (1 core)
1 thread at a time
IO state
Mem.
…
threads Process N
IO state
Mem.
…
threads
…
• Switch overhead: low (only CPU state)
• Thread creation: low • Protection
– CPU: yes – Memory/IO: No
• Sharing overhead: low (thread switch overhead low)
CPU state
CPU state
CPU state
CPU state
Lec 3.33 9/11/13 Anthony D. Joseph and John Canny CS162 ©UCB Fall 2013
Putting it together: Multi-Cores Process 1
CPU sched.
OS
IO state
Mem.
…
threads Process N
IO state
Mem.
…
threads
…
• Switch overhead: low (only CPU state)
• Thread creation: low • Protection
– CPU: yes – Memory/IO: No
• Sharing overhead: low (thread switch overhead low)
core 1 Core 2 Core 3 Core 4 CPU
4 threads at a time
CPU state
CPU state
CPU state
CPU state
Lec 3.34 9/11/13 Anthony D. Joseph and John Canny CS162 ©UCB Fall 2013
Putting it together: Hyper-Threading Process 1
CPU sched.
OS
IO state
Mem.
…
threads Process N
IO state
Mem.
…
threads
…
• Switch overhead between hardware-threads: very-low (done in hardware)
• Contention for ALUs/FPUs may hurt performance
core 1
CPU
core 2
core 3
core 4
8 threads at a time
hardware-threads (hyperthreading)
CPU state
CPU state
CPU state
CPU state
3.35 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9th Edition
Windows Threads
Windows implements the Windows API – primary API for Win 98, Win NT, Win 2000, Win XP, and Win 7
Implements the one-to-one mapping, kernel-level Each thread contains
A thread id Register set representing state of processor Separate user and kernel stacks for when thread runs in
user mode or kernel mode Private data storage area used by run-time libraries and
dynamic link libraries (DLLs) The register set, stacks, and private storage area are known as
the context of the thread
Lec 2.36 1/27/14 Anthony D. Joseph CS162 ©UCB Spring 2014
Examples of multithreaded programs
• Embedded systems – Elevators, Planes, Medical systems, Wristwatches – Single Program, concurrent operations
• Most modern OS kernels
– Internally concurrent because have to deal with concurrent requests by multiple users
– But no protection needed within kernel
• Database Servers – Access to shared data by many concurrent users – Also background utility processing must be done
Lec 2.37 1/27/14 Anthony D. Joseph CS162 ©UCB Spring 2014
Examples of multithreaded programs (con’t) • Network Servers
– Concurrent requests from network – Again, single program, multiple concurrent operations – File server, Web server, and airline reservation systems
• Parallel Programming (More than one physical CPU)
– Split program into multiple threads for parallelism – This is called Multiprocessing
• Some multiprocessors are actually uniprogrammed:
– Multiple threads in one address space but one program at a time
Lec 2.38 1/27/14 Anthony D. Joseph CS162 ©UCB Spring 2014
Classification
• Real operating systems have either – One or many address spaces – One or many threads per address space
Mach, OS/2, HP-UX, Win NT to 8, Solaris, OS X, Android, iOS
Embedded systems (Geoworks, VxWorks,
JavaOS,etc) JavaOS, Pilot(PC)
Traditional UNIX MS/DOS, early Macintosh
Many
One
# threads Per AS:
Many One
# of
add
r sp
aces
: