Top Banner
Opera&ng Systems Lecture 3: Four fundamental OS concepts Abstrac8ons I: Threads CS4410 Rachit Agarwal
40

lecture03 rachit

Oct 17, 2021

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: lecture03 rachit

Opera&ngSystems

Lecture3:FourfundamentalOSconcepts

Abstrac8onsI:Threads

CS4410

RachitAgarwal

Page 2: lecture03 rachit

Contextfortoday’slecture

• Lastlecture(andearlypartsoftoday’slecture):

• StudysomeofthebuildingblocksofanOS

• Understand“why”weneedthesebuildingblocks

• Andwhataretheconceptualchallengesindesigningthem

• Today,andnextcoupleoflectures

• UnderstandtheabstractionsofferedbytheOS

• Threads,Process,Virtualmemory,Files,Sockets,Signals,..

• Whytheyaredesignedthewaytheyaredesigned

• Whatarethetradeoffsindifferentdesigndecisions

• Someinterestingdetailsonhowtheyareimplemented

Page 3: lecture03 rachit

GoalofToday’sLecture

• WrapupdiscussiononfourfundamentalconceptsinOS

• Deeperdiveintothreads

Page 4: lecture03 rachit

Recall:WhatdoesanOSdo?

• Enablesconvenient“abstractions”forapplicationstoaccesshardware• CPU:threads

• Memory:virtualmemory

• Storagedevices:files

• Network:sockets

• Server:collectionofresourcesneededbyanapplication(processes,VM,..)

• Manageshardwareresources• Resourceallocation,sharingandisolation

• Implementscommonservicesforapplications• Security,protectionandauthentication

• Reliability

• Communication

• Input/outputoperations

• Programexecution

• ….

Page 5: lecture03 rachit

Recall:FourFundamentalOSConcepts

• Thread:ExecutionContext• Asingle,sequentialexecutioncontext

• Addressspace(withtranslation)• Program'sviewofmemoryisdistinctfromphysicalmemory

• Process:aninstanceofarunningprogram

• AddressSpace+OneormoreThreads+…

• Protection/Isolation• Onlythe“system”canaccesscertainresources

• Combinedwithtranslation,isolatesprogramsfromeachother

Page 6: lecture03 rachit

Recall:Threads• Definition:Asingle,sequentialexecutioncontext

• A“virtual”core• Executesasequenceofinstructions,inorder,onaphysicalcore

• Onlyonethinghappensatatime

• Challenges:• synchronization(correctness),scheduling(performance)

vCPU3vCPU2vCPU1

Shared Memory

vCPU1 vCPU2 vCPU3 vCPU1 vCPU2

Time

• Whythreads?

• Statisticalmultiplexing:improvedutilizationofphysicalcores

Page 7: lecture03 rachit

Recall:Virtualaddressspace

• Physicaladdressspace:wherethedataactuallyresides

• “Virtual”addressspace:wheretheprogramthinksthedataresides

• Whyvirtualaddressspace?

• Statisticalmultiplexing:improvedutilizationofphysicalmemory

• Protection/Isolation(notyetcovered)• ….

• Challenges?• Efficientaddresstranslation

Page 8: lecture03 rachit

Recall:Challengeofefficientaddresstranslation

• Programsusevirtualaddresses

• Asaprogramruns,virtualaddressestranslatedtophysicaladdresses

• Addresstranslationmustbeextremelylight-weight(inthecommoncase)

• Tokeeptheoverheadslow

• Twoideas:• Performaddresstranslationinhardware

• Maintainalookuptable(virtual—>physical)

• Toachieveefficiency:• Smallsizeoflookuptable(why?)

• Fastalgorithmstoperformalookup

Page 9: lecture03 rachit

Achievingefficiencyusing“pages”

• Dividevirtualaddressspacesintocontiguouschunksoffixedsize(sayX)• Calleachchunkapage(usuallyX=4096bytes)

• Mapeachpageto4KBofcontiguousphysicaladdressspace

• IfpagesizeisX,avirtualaddressvisat• (assumingaddresses/offsetsstartwith0)

• pagenumber:floor(v/X)

• Offset:v-X*floor(v/X)-1• E.g.,X=4096;v=4097isonpage1,offset0

• Pagesenableefficiency:• Smallerlookuptablesize

• ReducedbyafactorofX• Comparedtomappingeachindividualaddress

• Enablefasteralgorithmstoperformalookup(later)

Page 10: lecture03 rachit

Questions?

Page 11: lecture03 rachit

Today:FourFundamentalOSConcepts

• Thread:ExecutionContext• Asingle,sequentialexecutioncontext

• Addressspace(withtranslation)• Program'sviewofmemoryisdistinctfromphysicalmemory

• Process:aninstanceofarunningprogram

• AddressSpace+OneormoreThreads+…

• Protection/Isolation• Onlythe“system”canaccesscertainresources

• Combinedwithtranslation,isolatesprogramsfromeachother

Page 12: lecture03 rachit
Page 13: lecture03 rachit

Process

• Definition:executionenvironmentwithrestrictedrights

• Oneormorethreads

• Executionstate:everythingthatcanaffect,orbeaffectedby,athread• Code,data,registers,callstack,files,sockets,etc.

• Partoftheprocessstateis“owned”byindividualthreads• Partissharedamongallthreadsintheprocess

• Eachprocesshasa“state”—Processcontrolblock(PCB)

• Executionstateforeachthread• Schedulinginformation

• Informationaboutmemoryusedbytheprocess

• Informationaboutfiles,sockets,etc.

• ….

Page 14: lecture03 rachit
Page 15: lecture03 rachit

EvolutionofOSprocessmodel

• Earlyoperatingsystems:singletasking

• Singleprocess,singlethread• “switch”applicationsoverlongtimescales

• Problem?

• Late1970s:multitasking

• Multipleprocesses,singlethreadperprocess

• Shareresourcesacrossprocesses• Problem?

• 1990s:multitasking,multithreading

• Multipleprocesses,multiplethreads

• Challenges?

Page 16: lecture03 rachit

SingleandMultithreadedProcesses

• Whyhavemultiplethreadswithinthesameprocess?

• Threadsencapsulateconcurrency

Page 17: lecture03 rachit

Questions?

Page 18: lecture03 rachit

Today:FourFundamentalOSConcepts

• Thread:ExecutionContext• Asingle,sequentialexecutioncontext

• Addressspace(withtranslation)• Program'sviewofmemoryisdistinctfromphysicalmemory

• Process:aninstanceofarunningprogram

• AddressSpace+OneormoreThreads+…

• Protection/Isolation• Onlythe“system”canaccesscertainresources

• Combinedwithtranslation,isolatesprogramsfromeachother

Page 19: lecture03 rachit

AnOSmayrunmultipleconcurrentprocesses

Page 20: lecture03 rachit

Thecorechallengewithmultipleprocesses?

• Protection/Isolation/Sharing• Reliability:buggyprocessescanonlyhurtthemselves

• Security:aprocessdoesnothavetotrustotherprocesses• Fairness:agoodgranularitytoenforcefairutilizationofresources

• Mechanismstoenableisolation:

• Virtualization• Virtualcores,virtualaddressspace(inparticular)

• Dualmodeoperations

• OnlytheOScanaccesscertainresources

Page 21: lecture03 rachit

Dualmodeoperation

• Hardwareprovidesatleasttwomodesofoperations:

• Kernelmode(or“supervisor”/“protected”mode)

• Usermode

• Processes(i.e.,programsyourun)executeinusermode

• Certainoperationsareprohibitedwhenrunninginusermode

• E.g.,changingthepagetablepointer• Toperformprivilegedactions,processesrequestservicesfromtheOS

• Kernelexecutesinkernelmode

• Performsprivilegedactionstosupportrunningprocesses

• Configureshardwareforproperprotection(e.g.,addresstranslation)

• “Controlled”transitionsbetweenusermodeandkernelmode

• Systemcalls,interrupts,exceptions

Page 22: lecture03 rachit

UsertoKernelModeTransfers

• Syscalls• Processrequestsasystemservice,e.g.,exit

• Likeafunctioncall,but“outside”theprocess

• Interrupts• Externalasynchronousevent• e.g.,I/Ooperations

• Traporexception• Internalsynchronouseventinprocess• e.g.,protectionviolation(segmentationfault),divide-by-zero,…

Page 23: lecture03 rachit

Additionallayersofprotectionformodernsystems

• Inmanymodernlarge-scaledeployments

• RunacompleteOSina“virtualmachine”

• Packagealllibrariesassociatedwithanapplicationintoa“container”

• Moreonthislaterinthecourse

Page 24: lecture03 rachit

Questions?

Page 25: lecture03 rachit

AbstractionI:Threads

Page 26: lecture03 rachit

Divingonemoreleveldeeper:Threads

• Thread:Asingle,sequentialexecutioncontext• Asingleexecutionsequencethatcanbescheduledindependently

• Provideamechanismforconcurrencyandparallelism

• Protectionisanorthogonalconcept• Aprotectiondomaincancontainonethreadormore

Page 27: lecture03 rachit

Concurrencyvs.Parallelism

• Concurrencyisabouthandlingmultiplethings

• Parallelismisaboutdoingmultiplethingssimultaneously

• Example:Twothreadsonasingle-coresystemwithouthyperthreading…

• …executeconcurrently…

• …butnotinparallel

• Whatdoesitmeantoruntwothreadsconcurrently?

• Schedulerisfreetorunthreadsinanyorderandinterleaving

• Threadmayruntocompletionortime-sliceinchunks

Page 28: lecture03 rachit

NeedforThreads

• Considerthefollowingprogram:

main() { ComputePI(); PrintClassList(“classlist.txt”);}

•Whatoutputdoyouexpect?

•Wouldtheprogrameverprintoutclasslist?

• No!Why?

• ComputePIwouldneverfinish

Page 29: lecture03 rachit

WithThreads

• Versionofprogramwiththreads(loosesyntax):main() { create_thread(ComputePI()); create_thread(PrintClassList(“classlist.txt”));}

• Whatoutputdoyouexpect?

• Now,youwouldactuallyseetheclasslist

• Butonly“nowandthen”

• Illusion:infinitenumberofprocessors(potentiallyvaryingspeeds)

• create_thread:Spawnsanewthreadrunningthegivenprocedure• ShouldbehaveasifanotherCPUisrunningthegivenprocedure

Page 30: lecture03 rachit

ThreadsMask“Idle”periods

• Athreadisinoneofthefollowingthreestates:

• RUNNING—running

• READY—eligibletorun,butnotcurrentlyrunning

• BLOCKED—ineligibletorun

• Ifathreadcannotproceed(e.g.,waitingforanI/Orequesttobefinished)

• TheOSmarksitasBLOCKED

• Oncethethreadisready,theOSmarksitasREADY

• Cannowbescheduled

• Oncethethreadisscheduled,theOSmarksitasRUNNING

• Actuallyusingthephysicalcorenow

Page 31: lecture03 rachit

AnotherexampleforThreads

• Versionofprogramwiththreads(loosesyntax):main() { create_thread(RenderUserInterface); create_thread(PrintClassList(“classlist.txt”));}

• Whatisthebehaviorhere?

• Stillrespondtouserinput

• Whilereadingfileinthebackground

Page 32: lecture03 rachit

MultithreadedPrograms

• WhenyoucompileaCprogramandruntheexecutable

• Itcreatesaprocessthatisexecutingthatprogram

• Initially,thisnewprocesshasonethreadinitsownaddressspace

• Withcode,globals,etc.asspecifiedintheexecutable

• Howcanwemakeamultithreadedprocess?

• Aprocesscanissuessyscallstocreatenewthreads

• Thesenewthreadsarepartoftheprocess:

• Theyshareitsaddressspace

Page 33: lecture03 rachit

NewIdea:Fork-JoinPattern

• Mainthreadcreates(forks)collectionofsub-threadspassingthemargstoworkon…

• …andthenjoinswiththem,collectingresults.

create

exit

join

Page 34: lecture03 rachit

MemoryLayoutwithTwoThreads

• TwosetsofCPUregisters

• Twosetsofstacks

• Issues:

• Howdowepositionstacksrelativetoeachother?

• Whatmaximumsizeshouldwechooseforthestacks?

• Whathappensifthreadsviolatethis?

• Howmightyoucatchviolations?

Code

GlobalData

Heap

Stack1

Stack2

AddressSpace

0x000…

0xFFF…

Page 35: lecture03 rachit

ThreadAbstraction

• Illusion:infinitenumberofprocessors,potentiallyvaryingspeeds

• Reality:threadsexecutewithvariable“speed”

• Why?

• Dependsonschedulingpolicies

• Programsmustbedesignedtoworkwithanyschedule

Page 36: lecture03 rachit

Programmervs.ProcessorView

Page 37: lecture03 rachit

CorrectnesswithConcurrentThreads

• Goal:CorrectnessbyDesign

• Whatmakesthisachallenginggoal?

• Non-determinism:

• Schedulercanrunthreadsinany(non-deterministic)order

• Why?

• Schedulercanswitchthreadsatanytime

• Why?

• IndependentThreads

• Nostatesharedwithotherthreads

• Deterministic,reproducibleconditions

• CooperatingThreads

• Sharedstatebetweenmultiplethreads

Page 38: lecture03 rachit

RaceConditions

• Initiallyx==0andy==0

• Whatarethepossiblevaluesofxbelowafterallthreadsfinish?

• Mustbe1.ThreadBdoesnotinterferewithThreadA.

Thread Ax = 1;

Thread B

y = 2;

Page 39: lecture03 rachit

RaceConditions

• Initiallyx==0andy==0

• Whatarethepossiblevaluesofxbelow?

• 1or3or5(non-deterministic)

• RaceCondition:ThreadA“races”againstThreadB!

Thread Ax = y + 1;

Thread B

y = 2;y = y * 2;

Page 40: lecture03 rachit

Definitions

• Synchronization:• Threadcoordination,usuallyregardingshareddata

• MutualExclusion:

• Ensuringonlyonethreaddoesaparticularthingatatime

• Typeofsynchronization

• CriticalSection:• Partofcodethatcanbeexecutedbyexactlyonethreadatonce• Resultofmutualexclusion

• Lock:• Anobjectthatcanbeheldbyonlyonethreadatatime

• Providesmutualexclusion