operating systems: processes and threads

55
Operating Systems: Operating Systems: Processes and Threads Processes and Threads Week 1: Lecture 2, Thu 10.9.2009 Week 1: Lecture 2, Thu 10.9.2009 Tiina Niklander Tiina Niklander 1

Upload: others

Post on 30-May-2022

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Operating Systems: Processes and Threads

Operating Systems:Operating Systems:Processes and ThreadsProcesses and Threads

Week 1: Lecture 2, Thu 10.9.2009Week 1: Lecture 2, Thu 10.9.2009

Tiina NiklanderTiina Niklander

1

Page 2: Operating Systems: Processes and Threads

Process modelProcess model

2

Page 3: Operating Systems: Processes and Threads

ProcessProcess

is an activity that has ais an activity that has aprogram, input, outputprogram, input, outputand a state.and a state.Some terms:Some terms:Text/codeText/code = executable instructions= executable instructionsDataData = variables= variablesStackStack = work area= work area

Parameter passing to subroutines/system callsParameter passing to subroutines/system callsProcess Control Block, PCBProcess Control Block, PCB entry inentry in Process TableProcess Table

= management information= management information3

Page 4: Operating Systems: Processes and Threads

ProcessProcess

Sta Fig 3.124

Page 5: Operating Systems: Processes and Threads

Process modelProcess model

One physical program counter switches between processesOne physical program counter switches between processesConceptual model of 4 independent, sequential processesConceptual model of 4 independent, sequential processesOnly one program active at anyOnly one program active at any instant on one CPUinstant on one CPUpseudoparallelismpseudoparallelism

5

Page 6: Operating Systems: Processes and Threads

Process CreationProcess Creation

Principal events that cause process creationPrincipal events that cause process creation1.1. System initializationSystem initialization2.2. Execution of a process creation systemExecution of a process creation system3.3. User request to create a new processUser request to create a new process4.4. Initiation of a batch jobInitiation of a batch job

6

Page 7: Operating Systems: Processes and Threads

Process CreationProcess Creation

Operating system doesOperating system doesCreate PCBCreate PCB

OS ‘generates’ a unique IDOS ‘generates’ a unique IDAllocate memory for the processAllocate memory for the processInitiate PCBInitiate PCBLink PCB to other structuresLink PCB to other structures

Place to ReadyPlace to Ready--queue, link to parent process, etcqueue, link to parent process, etc

7

Page 8: Operating Systems: Processes and Threads

Process TerminationProcess Termination

Conditions which terminate processesConditions which terminate processes1.1. Normal exit (voluntary)Normal exit (voluntary)2.2. Error exit (voluntary)Error exit (voluntary)3.3. Fatal error (involuntary)Fatal error (involuntary)4.4. Killed by another process (involuntary)Killed by another process (involuntary)

8

Page 9: Operating Systems: Processes and Threads

Process HierarchiesProcess Hierarchies

Parent creates a child process, childParent creates a child process, child processprocess cancancreate its own processcreate its own processForms a hierarchyForms a hierarchy

UNIX calls this a "process group"UNIX calls this a "process group"

Windows has no concept of process hierarchyWindows has no concept of process hierarchyall processes are created equalall processes are created equal

9

Page 10: Operating Systems: Processes and Threads

Process States (1)Process States (1)

Possible process statesPossible process statesrunningrunningblockedblockedreadyready

Transitions between states shownTransitions between states shown10

Page 11: Operating Systems: Processes and Threads

Process statesProcess states

AB

C

D

11

Page 12: Operating Systems: Processes and Threads

Process statesProcess states

Sta Fig 3.8Sta Fig 3.812

Page 13: Operating Systems: Processes and Threads

Process Control BlockProcess Control Block

Fields of a process table entryFields of a process table entry13

Page 14: Operating Systems: Processes and Threads

Tasks on interruptTasks on interrupt

The process is not always changed in step 6,The process is not always changed in step 6,if running process can continue.if running process can continue.Process can be changed only at step 6.Process can be changed only at step 6.

14

Page 15: Operating Systems: Processes and Threads

ThreadsThreads

15

Page 16: Operating Systems: Processes and Threads

Word processor with three threadsWord processor with three threads

One thread interacts with userOne thread interacts with userOne thread handles reformatting in backgroundOne thread handles reformatting in backgroundOne thread handles disk backups in backgroundOne thread handles disk backups in background

16

Page 17: Operating Systems: Processes and Threads

Multithreaded web server using dispatcherMultithreaded web server using dispatcherDispatcher receivesDispatcher receivesrequestsrequestsHandles to an idle workerHandles to an idle workerthread for processingthread for processingSuitable model for such:Suitable model for such:finitefinite--state machinestate machine

17

Page 18: Operating Systems: Processes and Threads

Thread modelThread model

(a) Three processes each with one thread(a) Three processes each with one thread(b) One process with three threads(b) One process with three threads

18

Page 19: Operating Systems: Processes and Threads

Thread Model:Thread Model:ProcessProcess vsvs threadthread

Items shared by all threads in a processItems shared by all threads in a processItems private to eachItems private to each thread in the threadthread in the threadEach thread has its own stack!Each thread has its own stack!

19

Page 20: Operating Systems: Processes and Threads

Why threads?Why threads?Multiple parallel activities. Threads provide easier programmingMultiple parallel activities. Threads provide easier programmingmodelsmodelsFaster to create and destroy one thread than a whole processFaster to create and destroy one thread than a whole processWhen one thread waits, another might be able to executeWhen one thread waits, another might be able to executeShared data area of threads in one process. Efficient resourceShared data area of threads in one process. Efficient resourcesharing andsharing and easy communication.easy communication.

BUTBUTMutual exclusion and synchronization are fully programmer’sMutual exclusion and synchronization are fully programmer’sresponsibility (no support from OS or anything else)responsibility (no support from OS or anything else)

Concurrentprogrammingcourse

20

Page 21: Operating Systems: Processes and Threads

POSIX threads (pthreads)POSIX threads (pthreads)

IEEE standard for threads for portable thread programsIEEE standard for threads for portable thread programspthread_createpthread_create()()

Create a new threadCreate a new thread

pthread_exitpthread_exit()()Terminate the calling threadTerminate the calling thread

pthread_joinpthread_join()()Wait for a specific thread to exitWait for a specific thread to exit

pthread_yieldpthread_yield()()Release the CPU to let another thread runRelease the CPU to let another thread run

Functions for synchronization and mutual exclusionFunctions for synchronization and mutual exclusionAnd more than 50 other functionsAnd more than 50 other functions

21

Page 22: Operating Systems: Processes and Threads

UserUser--levellevel vsvs kernelkernel--level threadslevel threads

Tan08Fig 2-16

Kernel (or OS) is not aware ofKernel (or OS) is not aware ofthreads, schedules processesthreads, schedules processesUser process must dispatchUser process must dispatchthreads itselfthreads itself

All thread control and dispatchingdone by the kernelNo control on the user level

22

Page 23: Operating Systems: Processes and Threads

UserUser--level threadslevel threads

AdvantagesAdvantagesFast dispatchingFast dispatching

No mode switchNo mode switchNo interruptNo interruptNo process switch!No process switch!

Programmer can freelyProgrammer can freelychoose the schedulingchoose the schedulingmechanismmechanism

DisadvantagesDisadvantagesWhen one thread is blockedWhen one thread is blockedon system call, it blocks theon system call, it blocks thewhole process (and all otherwhole process (and all otherthreads)threads)Threads of one processThreads of one processcannot be executed oncannot be executed onseveral processorsseveral processorsconcurrentlyconcurrently

Remember: kernel dispatchesRemember: kernel dispatchesonly processes!only processes!

23

Page 24: Operating Systems: Processes and Threads

KernelKernel--level threadslevel threads

AdvantagesAdvantagesThreads of one process canThreads of one process canbe executed simultaneouslybe executed simultaneouslyon multiple processorson multiple processorsIf one thread is Blocked, theIf one thread is Blocked, theother threads of this processother threads of this processmay still continuemay still continueOften also the kernelOften also the kernelimplementation isimplementation ismultithreadedmultithreaded

DisadvantagesDisadvantagesDispatching a thread has twoDispatching a thread has twophases:phases:

Interrupt +, interrupt handlingInterrupt +, interrupt handlingand mode switchand mode switchDispatcher (and return to userDispatcher (and return to usermode)mode)

Slower than in userSlower than in user--levellevelthreadsthreads

24

Page 25: Operating Systems: Processes and Threads

Hybrid ImplementationsHybrid Implementations

MultiplexingMultiplexing useruser--level threads onto kernellevel threads onto kernel--level threadslevel threads

25

Page 26: Operating Systems: Processes and Threads

SolarisSolaris

26

Page 27: Operating Systems: Processes and Threads

Making singleMaking single--threaded code multithreadedthreaded code multithreaded

Global variablesGlobal variablesThreads may not be aware of others using the same variableThreads may not be aware of others using the same variableSee next slide for solutionsSee next slide for solutions

Library proceduresLibrary proceduresMight not be reentrant (second call to procedure before theMight not be reentrant (second call to procedure before thefirst one is finished is not safe)first one is finished is not safe)Solution: rewrite the library or use an excluding jacketSolution: rewrite the library or use an excluding jacket

SignalsSignalsNo simple solutionsNo simple solutions –– difficult already in single threaddifficult already in single thread

Stack managementStack managementHow to increase a thread’s stack in case of stack overflowHow to increase a thread’s stack in case of stack overflow

27

Page 28: Operating Systems: Processes and Threads

Threads and global variablesThreads and global variables

ConflictsConflicts between threads over thebetween threads over theuse of a globaluse of a global variablevariable

One solution:One solution:Prohibit global variablesProhibit global variables

Alternative:Alternative:Private global variablesPrivate global variablesAccessing these is tricky,Accessing these is tricky,language may not supportlanguage may not supportNew library proceduresNew library procedures

28

Page 29: Operating Systems: Processes and Threads

Interprocess CommunicationInterprocess CommunicationRace ConditionsRace Conditions

Two processes want to access shared memory at same timeTwo processes want to access shared memory at same time

29

Page 30: Operating Systems: Processes and Threads

Critical Regions (1)Critical Regions (1)

Four conditions to provide mutual exclusionFour conditions to provide mutual exclusion1.1. No two processes simultaneously in critical regionNo two processes simultaneously in critical region2.2. No assumptions made about speeds or numbers of CPUsNo assumptions made about speeds or numbers of CPUs3.3. No process running outside its critical region may blockNo process running outside its critical region may block

another processanother process4.4. No process must wait forever to enter its critical regionNo process must wait forever to enter its critical region

30

Page 31: Operating Systems: Processes and Threads

Critical Regions (2)Critical Regions (2)

Mutual exclusion using critical regionsMutual exclusion using critical regions

31

Page 32: Operating Systems: Processes and Threads

Mutual ExclusionMutual Exclusion

Busy WaitingBusy Waiting –– occuby the CPU while waitingoccuby the CPU while waitingSleep and WakeupSleep and Wakeup

SemaphoresSemaphoresMutexesMutexesMonitorsMonitorsMessage PassingMessage PassingBarriersBarriers

Concurrent ProgrammingRinnakkaisohjelmointi

32

Page 33: Operating Systems: Processes and Threads

SchedulingSchedulingIntroduction to Scheduling (1)Introduction to Scheduling (1)

Bursts of CPU usage alternate with periods of I/O waitBursts of CPU usage alternate with periods of I/O waita CPUa CPU--bound processbound processan I/O bound processan I/O bound process

33

Page 34: Operating Systems: Processes and Threads

Introduction to Scheduling (2)Introduction to Scheduling (2)

Scheduling Algorithm GoalsScheduling Algorithm Goals34

Page 35: Operating Systems: Processes and Threads

Scheduling in Batch Systems (1)Scheduling in Batch Systems (1)

An example of shortest job first schedulingAn example of shortest job first scheduling

35

Page 36: Operating Systems: Processes and Threads

Scheduling in Batch Systems (2)Scheduling in Batch Systems (2)

Three level schedulingThree level scheduling36

Page 37: Operating Systems: Processes and Threads

Scheduling in Interactive Systems (1)Scheduling in Interactive Systems (1)

Round Robin SchedulingRound Robin Schedulinglist oflist of runnablerunnable processesprocesseslist oflist of runnablerunnable processes after B uses up its quantumprocesses after B uses up its quantum

37

Page 38: Operating Systems: Processes and Threads

Scheduling in Interactive Systems (2)Scheduling in Interactive Systems (2)

A scheduling algorithm with four priority classesA scheduling algorithm with four priority classes38

Page 39: Operating Systems: Processes and Threads

Scheduling in RealScheduling in Real--Time SystemsTime Systems

Schedulable realSchedulable real--time systemtime systemGivenGiven

mm periodic eventsperiodic eventseventevent ii occurs within period Poccurs within period Pii and requires Cand requires Ciisecondsseconds

Then the load can only be handled ifThen the load can only be handled if

1

1m

i

i i

CP

39

Page 40: Operating Systems: Processes and Threads

Policy versus MechanismPolicy versus Mechanism

Separate what isSeparate what is allowedallowed to be done withto be done with howhowit is doneit is done

a process knows which of its children threads area process knows which of its children threads areimportant and need priorityimportant and need priority

Scheduling algorithm parameterizedScheduling algorithm parameterizedmechanism in the kernelmechanism in the kernel

Parameters filled in by user processesParameters filled in by user processespolicy set by user processpolicy set by user process

40

Page 41: Operating Systems: Processes and Threads

Thread Scheduling (1)Thread Scheduling (1)

Possible scheduling of threadsPossible scheduling of threads5050--msec process quantummsec process quantumthreads run 5threads run 5 msecmsec/CPU burst/CPU burst

User-level Kernel-level

41

Page 42: Operating Systems: Processes and Threads

Extra pages:Extra pages:Scheduling exampleScheduling example

42

Page 43: Operating Systems: Processes and Threads

43

CPU Scheduling:CPU Scheduling:Algorithms examplesAlgorithms examples

FirstFirst--ComeCome--FirstFirst--ServedServed FCFSFCFSRound RobinRound Robin RRRRVirtual Round RobinVirtual Round Robin VRRVRRShortest Process NextShortest Process Next SPNSPNShortest Remaining TimeShortest Remaining Time SRTSRTHighest Response Ratio NextHighest Response Ratio Next HRRNHRRNMultilevel FeedbackMultilevel Feedback feedbackfeedback

Fair Share SchedulingFair Share Scheduling FSSFSS

Page 44: Operating Systems: Processes and Threads

44

Process setProcess set

Service Time =Service Time = running time on CPUrunning time on CPUNo I/O in the example (unrealistic?)No I/O in the example (unrealistic?)

(Tbl 9.4 [Stal05])

Page 45: Operating Systems: Processes and Threads

45

FCFSFCFS –– First Come First ServedFirst Come First Served

(Fig 9.5 [Stal05])

R379

1212

avg. 8.6

oo

oo

o

S36452

4 (avg.)arrival time for B completion time for B

cpu time for B

Page 46: Operating Systems: Processes and Threads

46

RRRR –– Round RobinRound Robin

(Fig 9.5 [Stal05])

R4

161314

7

avg. 10.8

oo

oo

o

S36452

4 (avg.)

Page 47: Operating Systems: Processes and Threads

47

RRRR –– effect of the time sliceeffect of the time slice

(Fig 9.5 [Stal05])

R3

157

1411

avg. 10.0

oo

oo

o

S36452

4 (avg.)

Page 48: Operating Systems: Processes and Threads

48

Virtual RR:njonomalli

Page 49: Operating Systems: Processes and Threads

49

SPNSPN –– Shortest Process NextShortest Process Next

(Fig 9.5 [Stal05])

R37

1114

3

avg. 7.6

oo

oo

o

S36452

4 (avg.)

Page 50: Operating Systems: Processes and Threads

50

SRTSRT –– Shortest RemainingShortest RemainingTimeTime

oo

oo o

R3

134

142

avg. 7.2(Fig 9.5 [Stal05])

S36452

4 (avg.)

45

25

Page 51: Operating Systems: Processes and Threads

51

time spent waiting CPU + expected service timetime spent waiting CPU + expected service timeresponse ratio =response ratio = --------------------------------------------------------------------------------------------------------------------------

expected service timeexpected service time

HRRNHRRN –– Highest Response RatioHighest Response RatioNextNext

oo

oo

o

R379

147

avg. 8.0(Fig 9.5 [Stal05])

S36452

4 (avg.)(5+2)/2 (7+5)/5>

257

5

Page 52: Operating Systems: Processes and Threads

52

Multilevel FeedbackMultilevel Feedback(Fig 9.10 [Stal05])

Page 53: Operating Systems: Processes and Threads

53

Feedback q=1Feedback q=1

oo

oo

o

R4

181213

3

avg. 10.0(Fig 9.5 [Stal05])

1 2 31 2 3 4 5 6

1 2 3 41 2 3 4 5

1 2

S36452

4 (avg.)

mistake?

Page 54: Operating Systems: Processes and Threads

54

Feedback q=2Feedback q=2ii

oo

oo

o

R4

151414

6

keskim. 10.6(Fig 9.5 [Stal05])

1 2 31 2 3

1 2 31 2 3

1 2

S36452

4 (keskim.)

mistake?

Page 55: Operating Systems: Processes and Threads

ComparitionComparition Tbl 9.3 [Stal05]