43
Operating Systems OPERATING SYSTEMS: Lesson 4: Process Scheduling 1 Jesús Carretero Pérez David Expósito Singh José Daniel García Sánchez Francisco Javier García Blas Florin Isaila

OPERATING SYSTEMS: Lesson 4

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

OperatingSystems

OPERATING SYSTEMS:

Lesson 4:Process Scheduling

1

Jesús Carretero PérezDavid Expósito SinghJosé Daniel García SánchezFrancisco Javier García BlasFlorin Isaila

OperatingSystems

Content

• Processcreation.• Processtermination.• Processlifecycle.• Kindsofscheduling.• Schedulingalgorithms.

2

OperatingSystems

Processcreation

• OSprovidesmechanismtoallowaprocesstocreateotherprocesses→Systemcall.

• Processcreationcanberepeatedrecursivelyleadingtoa“familystructure” →Processtree.

• Resourceallocationfornewprocess:– DirectlyobtainedfromtheOS.– Parentmustgiveoutitsresourcestothechildprocessorsharepart

ofthemwithit.• Toavoidasystemhangbyindefinitelyreplicatingtheprocessresources.

3

OperatingSystems

Processhierarchy(pstree)

4

OperatingSystems

Processcreation

5

• Whenaprocessiscreated:

– Intermsofexecution:• Parentprocessrunsinparallelwithchildren.• Parentprocesswaitsuntilsomeorallofitschildrenhaveterminated.

– Intermsofmemoryspace:• Childprocessisacloneoftheparentprocess.• Childprocessisconvertedintoanotherprogramloadedinmemory.

OperatingSystems

UNIXprocesscreation

¨Unixfamilymakesdistinctionbetweenprocesscreationandnewprogramexecution.

¨ Systemcalltocreateanewprocessisfork()

¨ Thissystemcallcreatesacopyalmostidenticaloftheparentprocess.¨ Bothprocesses,parentandchild,

continueexecutioninparallel.¨ Parentgetsasaresultfromthefork()

callthechildPIDandchildgetsa0.¨ Someresourcesarenotinherited

(e.g.:pendingsignals).

Process HProcess P

Kernel

fork()pid H

0

6

OperatingSystems

Linuxprocesscreation

Get free entry in Process Table

Copy PCB from parent

fork:

Duplicate Memory Map from parent (including stacks)

State ß ready

PCB in ready queue

Return PID to parent

Return 0 to child

“Copies parent process and gives new identity to

child”

7

Also clean up signals, events,…

OperatingSystems

UNIXprocesscreation

• Childprocessmayinvoketheexec*() systemcall.– Changesitsmemoryimagewithadifferentprogram.

• Parentmaycontinuecreatingmorechildren,orwaitinguntilthecreatedchildfinishes.– wait() takestheprocessfromthe“Ready”queueuntilthechildhasterminated.

shProcess H

Kernel Diskvi

exec()

8

OperatingSystems

ProcesscreationinLinux

exec:

“Change memory image from a process using as a

new container a new one”

Free process memory image

Read executable

Create new image M à PCB

Load .text and .data sections

Create initial U stackCreate S stack: dir.

program start

Init PCB: regs.; PC ß dir OS RETI

9

OperatingSystems

CopyonWrite(COW)

¨ Inefficienciesofthefork()model:¨ Alotofdataiscopied,butdatacouldbe

sharedinstead.¨ Iffinallyanothermemoryimageis

loaded,isevenworseasallcopiesarediscarded

¨ManyUNIXsystemsuseCOW:¤ Copy-on-Write isatechniquetodelayor

avoidcopyingdatawhenperformingafork.

¤ DatapagesaresharedandmarkedasCOWsothatifamodification isapplied,thenacopyisdonetheprocess(parentandchild).

¤ Nowfork()onlycopiesthepagetablefromparent(butnotthepages)andcreatesanewPCBforchild.

Memory pages ofParent process

Page table in parent

process

PCB parent PCB child

Sharing go avoid duplication

Page table in child

process

10

OperatingSystems

Content

• Processcreation.• Processtermination.• Processlifecycle.• Kindsofscheduling.• Schedulingalgorithms.

11

OperatingSystems

Processtermination

• When aprocessfreesallitsallocatedresources.– Memory,openfiles,entriesintables,…

• andthekernelnotifiesthattoparentprocess.

• Aprocessmayterminatein2ways:• Voluntarily:exit()systemcall.• Involuntarily:

– Exceptions:dividebyzero,segmentviolation,…– Abortedbyuser(ctrl-c)orotherprocess(kill)

» i.e.:signalsthatcannotbehandledorignored.

12

OperatingSystems

Processtermination

• Whenaprocessterminatestwooutcomesarepossible:– Itschildrenarenotaffected.– Allchildrenalsoterminate →cascadetermination(e.g.VMSoperatingsystem)

• In Unix,– Terminatedchildprocessesarenowchildrenoftheinitprocess.

– Terminatedprocesschangestozombie stateuntilparentprocessgetsitsterminationcode.

13

OperatingSystems

WhenisPCBeliminated?

14

• ProcessterminationandPCBeliminationaretwodifferenttasks:

– Whenparentgetsinformationfromchild,datastructurescanberemoved.

– wait()systemcall:• Blocksprocessuntilachildterminates.• ReturnsPID oftheterminatedchild.

Code1.c

OperatingSystems

Content

• Processcreation.• Processtermination.• Processlifecycle.• Kindsofscheduling.• Schedulingalgorithms.

15

OperatingSystems

Processbasiclifecycle

Running

BlockedReady

Wait for event

End of blocking by event

End of slice

Dispatching

As many as processors

16

New Processes

Termination

OperatingSystems

• Information associated with each process• Process state• Program counter• CPU registers• CPU scheduling information• Memory-management information• Accounting information• I/O status information

• PCBs are stored in a global process table

Process Control Block (PCB)

17

OperatingSystems

Ready Queue And Various I/O Device Queues

18

OperatingSystems

Spawningtodisk(swap)

• Whenthere aremanyprocessinexecution,performancemaydegradeduetoexcessivememorypaging.– Solution:OperatingSystemmayneedtosendaprocesstotheswapareaindisk.

• Newprocessstates.– Blockedandsuspended.– Readyandsuspended.

19

OperatingSystems

Processlifecycle

Running

BlockedReady

Wait for event

End of blocking by event

End ofslice

Dispaching

As many as processors

20

New Processes

Termination

Ready andSuspended

Blocked and Suspended

Suspension SuspensionRecovery

End of blocking by event

OperatingSystems

Content

• Processcreation.• Processtermination.• Processlifecycle.• Kindsofscheduling.• Schedulingalgorithms.

21

OperatingSystems

BasicConcepts

• MaximumCPUutilizationobtainedwithmultiprogramming– HavingwhenpossibleatanytimetheCPUusedbyaprocess

• CPU–I/OBurstCycle– Processexecutionconsistsofacycle ofCPUexecutionandI/Owait

• CPUburstdistribution

22

OperatingSystems

AlternatingSequenceofCPUAndI/OBursts

23

OperatingSystems

Schedulinglevels

¨Shorttermscheduling:¤Selectsnextprocesstoexecute.

¨Mediumtermscheduling:¨ Selectprocesstobeaddedorretired(suspendedtoswap)

frommainmemory.

¨Longtermscheduling:¤Performadmissioncontrolofprocesses.¤Veryusedinbatchsystems.

24

OperatingSystems

Kindsofscheduling

• Non-preemptive.– ProcessinexecutionkeepsrunningonCPUwhileitisabletousetheCPU.

• Preemptive:– OperatingSystemmayacquiretheCPU,evicttheprocessandchangetheexecutiontoanotherprocess.

25

OperatingSystems

Schedulingdecisionpoints

• PointsintimewhenOSmayperformprocessscheduling:• Whenaprocessblockswaitingforanevent.

• Performasystemcall.• I/Orequest• Wait()invocation

• Whenaninterrupthappens.• Clockinterrupt.• I/Ointerrupt.

• Whenaprocessswitchesfromwaitingstatetoreadystate• I/Ocompletion

• Whenaprocess ends.• Nonpreemptive scheduling:1and4.

• Windows95,MacOS before8.• Preemptivescheduling:1,2,3,and4.

26

OperatingSystems

Dispatcher

• DispatchermodulegivescontroloftheCPUtotheprocessselectedbytheshort-termscheduler;thisinvolves:– switchingcontext– switchingtousermode– jumpingtotheproperlocationintheuserprogramtorestart

thatprogram

• Dispatchlatency– timeittakesforthedispatchertostoponeprocessandstartanotherrunning

27

OperatingSystems

Processqueues

• Readyprocessesarekeptinaqueue.

• Alternatives:– Singlequeue.– Queuesbytypesofprocesses.– Priorityqueues.

28

OperatingSystems

Content

• Processcreation.• Processtermination.• Processlifecycle.• Kindsofscheduling.• Schedulingalgorithms.

29

OperatingSystems

Scheduling:metrics

30

• CPUutilization:• PercentageoftimeCPUisused.• Goal:Maximize.

• Throughput:• Numberofjobsfinishedbyunitoftime.• Goal:Maximize.

• Turnaroundtime(Tq)• Overalltimeaprocessisinsystem.• Tq =Tf – Ti

• Tf:Finalizationtime.• Ti:Initiationtime.

• Goal:Minimize.

OperatingSystems

Scheduling:Metrics

31

• Servicetime(Ts):• Timedevotedtoproductivetasks(cpu,I/O).• Ts=Tcpu+TI/O

• Waitingtime(Tw):• Timeaprocessspendsinwaitingqueues.• Tw=Tq – Ts

• NormalizedTurnaroundtime(Tn):• RatiobetweenTurnaroundtimeandservicetime.• Tn =Tq/Ts• Indicationofexperienceddelay.

OperatingSystems

FCFS

32

• FirsttoComeFirsttoServe.– Non-preemptive.– Penalizesshortprocesses:Convoyeffect shortprocessbehindlongprocess

Process

Arrival Service

A 0 3B 2 6C 4 4D 6 5E 8 2

A A AB B B B B B

C C C CD D D D D

E E

OperatingSystems

FCFS:NormalizedTurnaroundTime

33

Process

Arrival Service Init End Turnaround

Wait NormalizedTurnaround

A 0 3 0 3 3 0 3/3=1B 2 6 3 9 7 1 7/6=1.16C 4 4 9 13 9 5 9/4=1.25D 6 5 13 18 12 7 12/5=2.4E 8 2 18 20 12 10 12/2=6

• AverageTurnaroundtime:4.6• AveragenormalizedTurnaroundtime:2.5

OperatingSystems

SJF

34

• ShortestJobFirst.• Non-preemptivealgorithm.• Selectsshortestjob.• Itcanonlybeappliedifdurationofeachjobisknown

beforehand.• SJFisoptimal– givesminimumaveragewaitingtimefora

givensetofprocesses– ThedifficultyisknowingthelengthofthenextCPUrequest

• Starvationpossibility:– Ifshortjobsarecontinuouslyarriving,longerjobsneverarein

positiontobeexecuted.

OperatingSystems

SJF

35

A A A

B B B B B B

E E

C C C C

D D D D D

Process

Arrival Service Init End Turnaround

Wait Normalized Turnaround

A 0 3 0 3 3 0 3/3=1B 2 6 3 9 7 1 7/6=1.16C 4 4 11 15 11 7 11/4=2.75D 6 5 15 20 14 9 14/5=2.8E 8 2 9 11 3 1 3/2=1.5

3.6 1.84

OperatingSystems

CyclicorRound-Robin

• KeepsaFIFOqueuewithprocessesready torun.• Aprocessisallocatedinto aprocessorforatimeslice.

• 10-100milliseconds• Aprocessgoesbacktotheready queuewhen:

• Itstimesliceexpires.• Aneventthattookittotheblockedqueuehappens.

• Aprocessgoestotheblocked queuewhen:• Startswaitingforanevent.

• Itisapreemptivealgorithm.• Itisimportanttoremindthateverycontextswitchleadstoadelay:

• Timeslice>>Contextswitchtime• Performance

– q large⇒ FIFO– qsmall⇒ qmustbelargewithrespecttocontextswitch,otherwiseoverheadis

toohigh

36

OperatingSystems

Round-Robin(q=1)

37

A A A

B B B B B B

EE

C C C C

DD D D D

Process

Arrival Service Init End Turnaround

Wait NormalizedTurnaround

A 0 3 0 4 4 1 4/3=1.33B 2 6 2 18 16 10 16/6=2.66C 4 4 5 17 13 9 13/4=3.25D 6 5 7 20 14 9 14/5=2.8E 8 2 10 15 7 5 7/2=3.5

6.8 2.71

OperatingSystems

Round-Robin(q=2)

38

A A A

B B B B B B

EE

C C C C

DD D D D

Process

Arrival Service Init End Turnaround

Wait NormalizedTurnaround

A 0 3 0 5 4 1 4/3=1.33B 2 6 2 17 16 10 16/6=2.66C 4 4 5 13 13 9 13/4=3.25D 6 5 9 20 14 9 14/5=2.8E 8 2 13 15 7 5 7/2=3.5

6 2.54

OperatingSystems

Round-Robin(q=4)

39

A A AB B B B B B

EE

C C C CDD D D D

Process

Arrival Service Init End Turnaround

Wait NormalizedTurnaround

A 0 3 0 3 3 0 3/3=1B 2 6 3 17 15 9 15/6=2.5C 4 4 7 11 7 3 7/4=1.75D 6 5 11 20 14 9 14/5=2.8E 8 2 17 19 11 9 11/2=5.5

6 2.71

OperatingSystems

PriorityScheduling

• Eachprocesshasapriorityassignedtoit.• Selectfirstprocesseswithhigherpriority.

– Preemptive– nonpreemptive

• Alternatives:– Fixedprioritiesà starvationproblem– lowpriorityprocessesmayneverexecute.

– Solution:agingmechanisms– astimeprogressesincreasethepriorityoftheprocess

40

OperatingSystems

SchedulinginWindows

41

• Maincharacteristics:• Prioritybased• Usestimeslices.• Preemptivescheduling.• Schedulingwithprocessoraffinity.

• Schedulingatthreadlevel(notprocesslevel).

• Athreadmayloosetheprocessorifanotherwithhigherprioritybecomesready.

• Schedulingdecisions:• Newthreadsà Ready.• Blockedthreadsreceivingitsevent à Ready.• Threadleavesprocessoriftimesliceexpires,itterminatesorbecomesblocked.

OperatingSystems

Summary

• ProcesscreationimpliesmemoryimageandPCBcreation.• Aprocesstransitionsthroughdifferentstatesduringits

execution.• Operatingsystemisresponsibleforprocessscheduling.• Schedulingmaybepreemptiveornon-preemptive.• Differentprocessschedulingalgorithmsmayfavoracertain

typeofprocesses.• ModernOperatingsystemsusepreemptivescheduling.

42

OperatingSystems

OPERATING SYSTEMS:

Lesson 4:Process Scheduling

43

Jesús Carretero PérezDavid Expósito SinghJosé Daniel García SánchezFrancisco Javier García BlasFlorin Isaila