50
Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2009 Operating System Concepts 8 th Edition, Chapter 5: CPU Scheduling

Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2009 Operating System Concepts – 8th Edition,

Chapter 5: CPU Scheduling

Page 2: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

2/50 Operating System Concepts – 7th Edition

CPU Scheduling

Basic Concepts

Scheduling Criteria

Scheduling Algorithms

Thread Scheduling

Multiple-Processor Scheduling

Operating Systems Examples

Algorithm Evaluation

Page 3: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

3/50 Operating System Concepts – 7th Edition

Basic Concepts

• Process Scheduling(프로세스 스케줄링)

• Long-term job scheduling , Short-term CPU scheduling, Medium-term swapping

• Burst (time)

• CPU Burst : Time it takes for the CPU to execute an operation

• I/O Burst : Time it takes for the CPU to wait for I/O task

• CPU-I/O burst cycle(버스트 주기)

» Cycle : CPU 실행(CPU burst) I/O 대기(I/O burst)

» CPU burst 유형

• I/O bound program : 많은 짧은 CPU burst 가짐

• CPU bound program : 적은 아주 긴 CPU burst 가짐

• CPU Scheduler

» Short-term scheduler : ready queue에서 선택

FIFO(First-In First-Out)큐

Priority queue(우선순위 큐), tree, Linked List

• Goal of processor scheduling :

Maximum CPU utilization obtained with multiprogramming

Page 4: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

4/50 Operating System Concepts – 7th Edition

Basic Concepts(cont.)

CPU burst vs. IO burst

(a) A CPU-bound process

(b) An I/O-bound process

4

Page 5: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

5/50 Operating System Concepts – 7th Edition

Basic Concepts(cont.)

Alternating Sequence of CPU And I/O Bursts

Page 6: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

6/50 Operating System Concepts – 7th Edition

Basic Concepts(cont.)

Histogram of CPU-burst Times

Page 7: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

7/50 Operating System Concepts – 7th Edition

Basic Concepts(cont.)

CPU scheduling 란 대기중인 프로세스들 중에서 하나를 선택하고 CPU를 할당하는 절차

Preemptive/Non-Preemptive Scheduling(선점/비선점스케줄링)

Preemptive Scheduling( 선점스케줄링)

특수하드웨어(timer)필요 , 공유 데이터에 대한 프로세스 동기화 필요

Windows95~, MacxOS8(Power PC)~

Non preemptive or Cooperative Scheduling(비선점 or 협조적스케줄링)

Not require special hardware(timer,특수 하드웨어 없음 )

Last until termination or I/O request( 종료 또는 I/O까지 계속 CPU점유)

MS-Windows , ~Windows 3.x, ~MacOS8 이전 버전

Kernel의 선점 처리

case 1(초기 Unix) : system call 완료 또는 I/O 완료할 때 까지 기다렸다가 문맥교환

실시간 컴퓨팅, 멀티프로세싱에 나쁨

case 2(대부분의 Unix) : interrupt 중 다른 interrupt enable(우선순위에 따라) 선점 처리

critical section(공유 데이터 수정하는 코드 부분)에 있는 동안 interrupt disable 해야 함

CPU scheduling decision time

1. running waiting : non preemptive

2. running ready (interrupt) : preemptive

3. waiting ready (I/O 완료) : preemptive

4. halt : non preemptive

Page 8: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

8/50 Operating System Concepts – 7th Edition

Basic Concepts(cont.)

분배기(Dispatcher) : 단기 스케줄러가 선택한 프로세스에서 CPU의 제어을

넘기고 다음의 작업을 담당한다.

문맥 교환

사용자 모드로 전환

프로그램의 적절한 위치로 점프하여 프로그램 재 시작

• dispatch latency(분배기가 한 프로세스를 종료시키고 다음 프로세스를 실행

시킬 때까지의 시간)가 짧아야 함

Scheduling Criteria

• 이용률(CPU utilization) : 40% ~ 90%

• 처리율(throughput) : 처리된 프로세스 개수/시간 단위

• 반환시간(turnaround time) : 프로세스가 system in system out 걸린 시간

• 대기시간(waiting time) : ready queue에서 기다린 시간

• 응답시간(response time) : 대화형 시스템에서 첫 응답까지의 시간

Page 9: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

9/50 Operating System Concepts – 7th Edition

Scheduling Algorithms

Criteria(척도) : Average waiting time(평균 대기 시간)

Single processor algorithm(단일 프로세서 알고리즘)

1. First-Come, First-Served Scheduling(선입 선처리 스케줄링)

2. Shortest-Job-First Scheduling(최소 작업 우선스케줄링)

3. Priority Scheduling) (우선순위스케줄링)

4. Round-Robin Scheduling (순환 할당 스케줄링)

5. Multilevel Queue Scheduling (다단계 큐 스케줄링)

6. Multilevel Feedback Queue (다단계 귀환 큐 스케줄링)

Thread scheduling (스레드 스케줄링)

Multiple-Processor Scheduling (다중 프로세서 스케줄링)

Realtime Sdheculing(실시간 스케줄링)

EDF (Earliest Deadline First)

Rate Monotonic

Rate Monotonic vs. EDF

Examples(예)

Solaris 2 Scheduling,

Windows XP Scheduling,

Linux Scheduling

Page 10: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

10/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

1. First-Come, First-Served) (선입 선처리스케줄링)

프로세스가 준비완료 큐에 진입할 때 큐의 맨 끝에 프로세스의 PCB를

연결한다. CPU가 자유상태가 되면 큐의 맨 앞에 있는 프로세스를

할당한다.

들어온 순서대로 처리, e.g. supermarket, bank tellers, McDonalds, etc

FIFO queue : First-in, First-out

convoy effect (호위 효과) : 큰 job 하나가 끝나기를 모두 기다림 (CPU-

bound process가 끝나기를 I/O bounded process들이 기다림)

Non-preemptive임(time-sharing에서는 곤란)

Jobs are treated equally: no starvation

Page 11: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

11/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example 1 FCFS

Process Burst Time

P1 24

P2 3

P3 3

프로세스들이 P1 , P2 , P3 순으로 도착한 경우

스케줄링을 위한 간트 차트(Gantt Chart):

Waiting time (대기시간) P1 : 0 P2 : 24; P3 : 27

Average waiting time (평균대기시간): (0 + 24 + 27)/3 = 17

Convoy effect(호위효과)

P1 P2 P3

24 27 30 0

Page 12: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

12/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example 2. FCFS

프로세스 도착 순서가 P2 , P3 , P1 이면

스케줄을 위한 간트 차트(Gantt chart)는:

Waiting time (대기시간) P1 : 6 P2 : 0 P3 : 3

Average waiting time (평균대기시간) : (6 + 0 + 3)/3 = 3

Much better than previous case!

P1 P3 P2

6 3 30 0

Page 13: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

13/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

2. Shortest-Job-First Scheduling(최소 작업 우선 스케줄링)

CPU burst 시간이 가장 짧은 프로세스를 먼저 실행 시킨다.

Two approaches :

Non-preemptive SJF

Preemptive SJF = Shortest Remaining Time First Scheduling

Optimal(최적)

Demerit(단점) : Starvation(기아 상태)

Long-term Scheduling에 좋음 프로세스 시간의 사용자 예측 치 이용

Short-term Scheduling에는 덜 좋음 차기 CPU burst 시간 파악이 어려워서

차기 CPU 버스트 시간 예측 모델

HRN(Highest-Response-ratio Next) 스케줄링

1971 Brinch Hansen

SJF의 단점 보완

Dynamic priority = (time waiting + service time) / (service time)

오래 기다린 프로세스는 time waiting이 증가하므로 priority 커지고

Short process일수록 priority 커짐

Non-preemptive 였음

Page 14: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

14/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example Non-preemptive-SJF

SJF (non-preemptive)

Average waiting time = (0 + 6 + 3 + 7)/4 = 4 P1 0=0-0 P2:8-2.0=6 P3:7-4.0=3 P4:12-5.0=7 0: P1(7) =>P1(7) p1(7) ~ 7:P2(4),P3(1),P4(4) => P3(1) p3(1) ~ 8: P2(4),P4(4) =>P2(4) p2(4) ~ 12:P4(4)=>P4(4) p4(4) ~ 16 14

Process Arrival Time Burst Time

P1 0.0 7

P2 2.0 4

P3 4.0 1

P4 5.0 4

Page 15: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

15/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example Preemptive SJF

SJF (preemptive) (= SRTF)

Average waiting time = (9 + 1 + 0 +2)/4 = 3 P1:0-0 + 11-2=9 P2:2-2.0 + 5-4=1 P3=4-4.0=0 P4:7-5=2

Process Arrival Time Burst Time

P1 0.0 7

P2 2.0 4

P3 4.0 1

P4 5.0 4

Page 16: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

16/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example, non-preemptive / preemptive SJF

Gantt Chart ?

Non-preemptive SJF algorithm

Average waiting time (평균대기시간) = ( + + ) / 3 =

Average turn-around time(평균반환시간)= ( + + ) / 3 =

Preemptive SJF algorithm

Average waiting time (평균대기시간) = ( + + ) / 3 =

Average turn-around time(평균반환시간)= ( + + ) / 3 =

Process Arrival Time Burst Time

P1 0.0 24

P2 2.0 3

P3 3.0 2

0

Page 17: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

17/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Determining Length of Next CPU Burst

다음의 CPU burst 시간을 예측

이전 CPU 버스트 시간들의 지수적 편균(exponential averaging)으로 예측

가능

Prediction of the Length of

the Next CPU Burst

.1 1 nnn t

:Define 4.

10 , 3.

burst CPUnext for the valuepredicted 2.

burst CPU oflength actual 1.

1

n

th

n nt

66*5.06*5.01

68*5.04*5.01

810*5.06*5.01

6 ,5.0,10

223

112

001

00

t

t

t

t

Page 18: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

18/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

3. Priority Scheduling(우선 순위 스케줄링)

높은 우선 순위의 프로세스를 먼저

ready queue : priority queue

FCFS : equal priority(non-priority)

SJF : priority : Preemptive ,non-preemptive

Priority 에 영향을 미치는 OS 내부요인

시간제한(time limit), 메모리 요구량, 오픈 파일 수, (average I/O

burst)/(average CPU burst) 비율 등

Priority 에 영향을 미치는 OS 외부요인

프로세스의 중요도, 컴퓨터사용료 형태와 금액, 작업부서,정치적

요인 등

무한정지(blocking) 또는 기아상태(starvation)

Aging : 재기시간이 길어지면 우선순위를 높여준다.

Page 19: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

19/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Implementation of priority scheduling

Abstractly modeled as multiple “priority queues”

Put ready job on Queue associated with its priority

Page 20: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

20/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

4. Round Robin(RR) Sheduling(순환할당 스케줄링)

FCFS +preemptive scheduling

Circular ready queue (FIFO)

time quantum : 프로세스가 CPU를 사용하는 시간 보통 10-100 milliseconds.

Performance

quantum -> : FIFO

quantum -> 0 : processor sharing

If small, then context switches are frequent incurring high overhead

(CPU utilization drops)

If large, then response time drops

A rule of thumb: 80% of the CPU bursts should be shorter than the time

quantum

Page 21: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

21/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example of RR with Time Quantum = 4

Process Burst Time

P1 24

P2 3

P3 3

The Gantt chart

Average waiting time (평균대기시간) : (?+?+?) / 3 = 5 3(SJF)

Average turnaround time(평균반환시간) : (30+7+10) / 3 = 15.6 3(SJF)

일반적으로 SJF보다 평균반환시간(average turnaround)은 길지만 응답시간(response time)은 짧다. queue : p1(24),p2(3),p3(3) 0 : p1(24) : p2(3),p3(3) timer 4:p2(3) : p3(3),p1(20) release 7 : p3(3) : p1(20), release 10:p1(20) : timer 14:p1(16): timer 18:p1(12): timer 22:p1(8): timer 26:p1(4): timer 30: * lease :non-preempted, timer : preempted

P1 P2 P3 P1 P1 P1 P1 P1

0 4 7 10 14 18 22 26 30

Page 22: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

22/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example, RR with Time Quantum = 20

Process Burst Time

P1 53

P2 17

P3 68

P4 24

The Gantt chart is:

Average waiting time (평균대기시간) : ( ? + ? + ? + ? )/4 = ?

Average turnaround time(평균반환시간) : ( ? + ? + ? + ? )/4 = ?

P1 P2 P3 P4 P1 P3 P4 P1 P3 P3

0 20 37 57 77 97 117 121 134 154 162

Page 23: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

23/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

그림 5.4 작은 할당량이 문맥교환을 증가시키는 이유

Time Quantum and Context Switch Time

Page 24: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

24/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

At Q=5 , turnaround time=?+?+?+?=12.2

그림 5.5 총 처리시간이 시간 할당량에 따라 변하는 모습

Turnaround Time Varies With The Time Quantum

Page 25: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

25/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

5. Multilevel Queue Scheduling(다단계 큐 스케줄링 )

프로세스는 우선 순위가 다른 여러 개의 큐 중 하나에 영원히 할당됨

(그림 5.6)

각 Queue는 자신의 고유한 Scheduling Algorithm 가짐

Foreground (interactive) queue : RR알고리즘

Background (batch) queue : FCFS알고리즘

Queue들 사이의 Scheduling : fixed priority preemptive scheduling (고정

우선 순위 선점 스케줄링)

큐 사이의 CPU time slice 할당 예

80% for RR

20% for FCFS

스케줄링 부담 적으나 융통성이 적음

Page 26: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

26/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

그림 5.6 다단계 큐 스케줄링

Page 27: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

27/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

6. Multilevel Feedback Queue Scheduling (다단계 피드백 큐 스케줄링 )

프로세스가 여러 큐 사이를 이동 (그림 5.7)

짧은 프로세스(I/O bound, interactive processes)가 우선

긴 프로세스는 자꾸 낮은 큐로 이동

aging(오래 기다리면 우선순위 높여 기아 상태 예방)

preemptive 임(큐 사이)

the most sophisticated, the most complex

가장 일반적 => 해당 시스템에 맞게 설정해야(configure)

큐의 개수

각 큐의 스케줄링 알고리즘

높은 우선 순위로 올려 주는 시기

낮은 우선 순위로 내려 주는 시기

어느 큐에 들어갈 것인가

Page 28: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

28/50 Operating System Concepts – 7th Edition

Scheduling Algorithms(cont.)

Example of Multi level feedback queue algorithm

Three queues:

Q0 – time quantum 8 milliseconds

Q1 – time quantum 16 milliseconds

Q2 – FCFS

Scheduling

FCFS queue Q0 에 새로 들어온 작업이 8 milliseconds 동안 CPU를 받고도 작업이

끝나지 않으면 선점되어 queue Q1으로 이동

Q1의 작업은 FCFS로 16 additional milliseconds을 받고 그래도 끝나지 않으면

선점되어 queue Q2로 이동

그림 5.7 다단계 피드백 큐

Q0

Q1

Q2

Page 29: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

29/50 Operating System Concepts – 7th Edition

Thread Scheduling Two types of thread scheduling(2 스레드 지원 수준)

User level: process local scheduling

threads library가 사용 가능한 LWP에 thread를 할당 (실제로 CPU 차지했다는 뜻 아님)

Kernel level: system global scheduling

kernel이 다음 실행할 kernel thread를 결정 (CPU 차지)

pthread scheduling

프로세스-경쟁-범위(process-contention scope; PCS): pthread library가 사용 가능한 LWP에

user-level thread 할당, CPU 차지하기 위한 투쟁이 한 프로세스 내에서 일어남

PTHREAD_SCOPE_PROCESS

many-to-many mapping

시스템-경쟁-범위(system-contention scope; SCS): kernel이 CPU 차지할 kernel thread 결정,

CPU 차지 위한 투쟁이 전체 시스템에서 일어남 (Linux, Mac OS는 시스템-경쟁-범위만 지원)

PTHREAD_SCOPE_SYSTEM

one-to-one mapping

pthread IPC

pthread_attr_setscope(pthread_attr-t *attr, int scope)

pthread_attr_getscope(pthread_attr-t *attr, int *scope)

스레드 매핑 모델별 적용

many-to-many 또는 many-to-one: PCS & SCS

one-to-one: SCS만 사용 (Linux, Windows XP, Solaris 9)

Page 30: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

30/50 Operating System Concepts – 7th Edition

Pthread Scheduling API for POSIX

#include <pthread.h>

#include <stdio.h>

#define NUM_THREADS 5

int main(int argc, char *argv[])

{

int I, scope;

pthread_t tid[NUM_THREADS];

pthread_attr_t attr;

/* get the default attributes */

pthread_attr_init(&attr); /* first inquire on the current scope */ if (pthread_attr_getscope(&attr, &scope) != 0) printf(stderr, “Unable to get scheduling scope\n”); else { if (scope == PTHREAD_SCOPE_PROCESS) pritnf(“PTHREAD_SCOPE_PROCESS”); else if (scope == PTHREAD_SCOPE_SYSTEM) pritnf(“PTHREAD_SCOPE_SYSTEM”); else printf(stderr,”Illegal scope value.\n”); }

/* set the scheduling algorithm to PCS(PROCESS) or (SCS)SYSTEM */

pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

/* set the scheduling policy - FIFO, RT, or OTHER

pthread_attr_setschedpolicy(&attr, SCHED OTHER); */

/* create the threads */

for (i = 0; i < NUM_THREADS; i++)

pthread_create(&tid[i],&attr,runner,NULL);

/* now join on each thread */

for (i = 0; i < NUM_THREADS; i++)

pthread_join(tid[i], NULL);

}

/* Each thread will begin control in this function */

void *runner(void *param)

{

/* do some work */

printf("I am a thread\n");

pthread exit(0);

}

Page 31: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

31/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling

동종 다중 프로세서(homogeneous multiprocessor)

프로세서는 큐에 있는 어떤 프로세스(any processes)든 실행: 부하 공유(load sharing)

별도 준비 큐(separate ready queue): unfair SMP 경우 load balancing 필요할까?

공동 준비 큐(common ready queue): fair SMP 경우 load balancing 필요할까?

AMP(Asymmetric Multiprocessing): 비대칭적 스케줄링 (asymmetric scheduling)

한 프로세서(master)가 다른 프로세서(slaves) 스케줄링

– master server : all system activity, client processors: user code only

master만 kernel system data structure에 접근 가능

– 공유 자료구조 접근 동기화 필요 없어 처리가 간단

SMP(Symmetric Multiprocessing): 대칭적 스케줄링 (symmetric scheduling)

각 프로세서가 스스로 스케줄링(self-scheduling)

공유 자료구조 접근에 대한 세심한 처리 필요

대부분의 현대 OS가 지원: Windows XP, Windows 2000, Solaris, Linux, Max OS X

처리기 친화성(processor affinity): 한 프로세서에서 작업하면 cash memory hit-ratio

높아져 효율적

약한 친화성(soft affinity): 친근 노력하나 프로세스 이주(process migration) 발생 가능

강한 친화성(hard affinity): 절대 친근 보장, 이주 불허도 가능 (예, Linux에서 시스템

호출로 요청)

부하 균형(load balancing): 별도 준비 큐 경우 일 부담의 균등 분배

push migration: 과부하 프로세서가 자신의 프로세스를 노는 프로세서로 이주시킴

pull migration: 노는 프로세서가 바쁜 프로세서에서 대기 중인 프로세스를 끌어옴

– Linux scheduler는 push & pull 모두 지원

이종 다중 프로세서(heterogeneous multiprocessor) = 분산 시스템

컴파일 된 프로세스들의 기계어가 실행하고자 하는 프로세서의 기계어와 동일한 경우만

실행 가능

Page 32: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

32/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling(cont.)

Symmetric multithreading(SMT)

Hyper-threading technology in Intel company

OS offers logical processor to each thread as if they run in each

physical processors.

그림 5.8 전형적인 SMT 구조

Page 33: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

33/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling(cont.)

SMP(Symmetric Multiprocessing) Architecture

그림 5.8 전형적인 SMT 구조

Page 34: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

34/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling(cont.)

NUMA (Non-Uniform Memory Access and CPU Scheduling

같은 보드에 있는 CPU의 메모리 접근시간이 더 적은 경우 강한 친화성(affinity)

Page 35: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

35/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling(cont.)

멀티코어 프로세서 (Multicore Processors)

최근 추세는 하나의 칩에 다수의 프로세서를 위치시킴

빠르고 파워 소모 적음

각 코어가 독자적으로 다중 스레드 처리하는 추세

멀티스레디드 프로세서 코어(multithreaded processor cores)

메모리의 데이터가 사용 가능할 때까지 상당한 메모리 지연(memory stall) 시간이 있음을

발견, 하나의 코어에 2개 이상의 하드웨어 스레드를 할당하여 메모리 지연시간을 최대한

활용

Intel Itanium: dual-threaded dual-core system = 4 logical processors,

urgency(0~7) priority hardware thread scheduling

UltraSPARC T1 CPU: 8 cores * 4 hardware threads per core = 32 logical processors,

simple RR hardware thread scheduling

Memory stall (fig.5.10, 8th) Multithread multicore system(Fig. 5.11, 8th)

Page 36: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

36/50 Operating System Concepts – 7th Edition

Multiple-Processor Scheduling(cont.)

A Dual-Core Design

Page 37: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

37/50 Operating System Concepts – 7th Edition

Operating System Examples

Example

Solaris scheduling ,Windows XP scheduling, Linux scheduling

Solaris 2 scheduling 우선순위 기반 스레드 스케줄링(priority-based process scheduling)

6 classes (OSC version 8)

(TS)시분할(time sharing): default class

– multi-level feedback queue scheduling

– 우선순위가 높을수록, time slice(20ms) 작고, 우선순위가 낮을수록 time slice(200ms) 큼

– CPU-bound processes 우선순위 낮아짐

– sleep에서 복귀한 스레드는 높은 우선순위

(IA)대화형(interactive)

– multi-level feedback queue scheduling

– windowing application에 높은 우선순위

(RT) 실시간(real time): 최상위 우선순위

(SYS)시스템(system): 우선순위 결정된 후 불변

(FSS)공평 공유(fair share): CPU 공유량을 기준으로 스케줄

(FP) 고정우선순위(fixed priority): 시분할 스레드와 같은 우선순위이나 고정

Scheduler가 class-specific priorities를 global priorities로 변환

우선순위 같을 때는 round-robin

수행 중인 thread가 멈추는 경우

blocks

time slice 완료

더 높은 우선순위의 thread가 선점(preempt)

Page 38: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

38/50 Operating System Concepts – 7th Edition

Solaris 2 Scheduling

Page 39: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

39/50 Operating System Concepts – 7th Edition

Solaris 2 Scheduling

(ms)

Low high

대화형과 시분할 스레드를 위한 Solaris 디스패치 테이블 (Solaris Dispatch Table for time-sharing and interactive threads)

※ Solaris & Windows XP: 높은 우선순위 프로세스에 짧은 time quantum 할당

Page 40: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

40/50 Operating System Concepts – 7th Edition

• 32-level priority scheme • 0: memory management • 1~15: variable class • 16~31: real-time class

• 각 우선순위마다 하나의 큐 가짐 (a queue for each scheduling priority) • idle thread: ready thread 없을 때 dispatcher가 실행 • 보통 NORMAL_PRIORITY_CLASS, base priority=normal • 1 time quantum 받은 후 우선순위 낮아짐, 기본우선순위 이하로는 제한(cpu burst process의 독점을 방지)

• 대화형 스레드(interactive threads )에 좋은 응답시간 (response times) 제공 방안 » 대기후 priority boost(높임): keybord I/O boost > disk I/O boost » 스크린에서 활성화된 전위 프로세스(foreground process)에게 활성화되지 않은 후위

프로세스(background process)보다 3배 많은 time quantum 부여

Windows XP Scheduling

priority class→

relative priority↓

base priority=normal

불변 가변 가변 가변 가변 가변

Windows XP Priorities

Page 41: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

41/50 Operating System Concepts – 7th Edition

Windows Thread Scheduling Example(c#)

Thread.Proity Property Example

Namespace: System.Threading

Assembly: mscorlib (in mscorlib.dll)

System.Threading.ThreadPriority public enum ThreadPriority {Lowest,BelowNormal,Normal,AboveNoraml,Higest}

Thread T = new Thread(new ThreadStart(p.method));

T.Priority = ThreaPriority.BelowNormal;

T.Start();

예제 시나리오

쓰레드 생성

– T1 :Normal Priority,

– T2 : Below Normal Priority

두 프로세스가 동시에 정수를 세게하고 10초 후에 정지시키고

센 수를 점검하여 T1의 수가 더 큰지를 점검한다.

즉 Thread Scheduling에 의하여 우선순위가 높은 Thread가 더 많이 CPU를

사용을 배정하여 더 셀수 있었는지를 검증

Page 42: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

42/50 Operating System Concepts – 7th Edition

Windows Thread Scheduling Example(c#)

static void Main() { PriorityTest p = new PriorityTest(); Thread T1=new ThreadStart(p.ThreadMethod); Thread T2=new ThreadStart(p.ThreadMethod);

T1.Name=“ThreaOne”; //T1 : Normal Prioty T2.Name=“ThreadTwo; T2.Prioty = ThreaPrioty.BelowNormal; T1.Start(); T2.Start(); Thread.Sleep(10000); p.LoopSwitch=false;

class PriorityTest { bool loopSwitch; public PriorityTest() { loopSwitch = true; } public bool LoopSwitch { set{ loopSwitch = value; } } public void ThreadMethod() { long threadCount = 0; while(loopSwitch) { threadCount++; } Console.WriteLine( "{0} with {1,11} priority has a count = {2,13}", Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), threadCount.ToString("N0"));

} } 실행 결과

Page 43: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

43/50 Operating System Concepts – 7th Edition

Linux Scheduling (Linux kernel 2.5)

Linux kernel version 2.5 이후

SMP 지원 향상: processor affinity, load balancing

공평 몫 스케줄링 (fair-share scheduling) 지원

interactive task 지원

Linux scheduler: preemptive, priority-based algorithm

2 priority ranges: 낮은 값이 높은 우선순위

real-time tasks: 0~99

other tasks (nice): 100~140

긴 sleep time (interactive): nice value -5

짧은 sleep time (CPU-bound): nice value +5

time-quantum 할당

높은 우선순위 프로세스 : 긴 time-quantum 할당 (Solaris, Windows XP 등 대부분 OS와 다름)

각 프로세서는 자신의 runqueue (active array, expired array) 유지

Active queue(array): time quantum이 남은 프로세스

Expired queue(array): time quantum 소진한 프로세스

한번 time quantum 받은 프로세스는 expired queue로 이동

active array의 모든 프로세스들이 time quantum 소진하면, 두 array 교환

Page 44: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

44/50 Operating System Concepts – 7th Edition

Linux Scheduling (Linux kernel 2.5)

Priorities and Time-slice length

Constant order O(1) scheduling time

Two priority ranges: time-sharing and real-time

Real-time range from 0 to 99 and nice value from 100 to 140

Page 45: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

45/50 Operating System Concepts – 7th Edition

Linux Scheduling (Linux kernel 2.5)

우선순위에 따라 인덱스 된 태스크 리스트 (List of Tasks Indexed According to Priorities)

Page 46: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

46/50 Operating System Concepts – 7th Edition

Algorithm Evaluation(알고리즘 평가)

결정론적 모델링(Deterministic Modeling)

작업부하(workload)에 대한 알고리즘 성능 비교( 5.7.1절 예제(p205-206) )

반환시간

대기시간 등

CPU 버스트 시간 등 많은 정확한 정보 요구

큐잉 모형(Queueing Models)

CPU-I/O 버스트 뿐 아니라 프로세스 도착시간의 분포도 평가에 고려해야

도착율과 서비스율 알면 이용율, 평균 큐 길이, 평균대기시간 알 수 있음

Little의 공식 : 평균 큐 길이 n = x W = (도착 율) x (평균대기 시간) (예) 초당 평균 7( )개 프로세스가 도착하고, 큐에 평균 14(n)개 프로세스가 있다면, 평균대기시간(W)은

2초

모의 실험(Simulations)

소프트웨어 자료구조로 clock variable, system state variables등 표현하고 통계

사건 분포는 수학적(균일, 지수, 포아송), 또는 경험적으로 정의

사건 생성 순서 정보 제공 위해 trace tapes 이용

정확하나 비용이 많이 듬

구현(Implementation)

가장 정확하나 비용 많고 사용자 적응이 문제

가장 융통성 있는 스케줄링 알고리즘(flexible scheduling algorithm)

tunable scheduling

• 시스템 관리자가 응용 영역에 따라 스케줄러 변수들을 변경할 수 있음

» 몇몇 Unix 버전에서 세밀한 tuning 가능

• Yield() 나 setPriority() API 이용하여 응용의 동작 예측 가능하게 함

Page 47: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

47/50 Operating System Concepts – 7th Edition

Algorithm Evaluation(알고리즘 평가)

Evaluation of CPU schedulers by Simulation

Page 48: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

48/50 Operating System Concepts – 7th Edition

Algorithm Evaluation(알고리즘 평가)

Deterministic modeling 예(p205)

Process : p1 p2 p3 p4 p5

Burst time(ms) : 10 29 3 7 12

FCFS scheduling algorithm

Averaging waiting time : (10+39+42+49)/5 = 28 ms

SJF scheduling algorithm(p 205)

Averaging waiting time : (10 + 32+0+3+20)/5=13 ms

Page 49: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

49/50 Operating System Concepts – 7th Edition

Algorithm Evaluation(알고리즘 평가)

Deterministic modeling 예(p206)

Process : p1 p2 p3 p4 p5

Burst time(ms) : 10 29 3 7 12

RR at time quantum = 10ms

Averaging waiting time : (0+32+20+23+40)/5 = 23 ms

p1 : 0

p2 : 10+20+2 =32

p3 : 20

p4 : 23

p5 : 30+10=40

Page 50: Chapter 5: CPU Scheduling - IISPL() · 2012-10-09 · Operating System Concepts –7th Edition 3/50 Basic Concepts • Process Scheduling(프로세스 스케줄링) • Long-term

Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2009 Operating System Concepts – 8th Edition,

End of Chapter 5