You are on page 1of 7

InvestigatingSynchronisation

Introduction
Attheendofthislabyoushouldbeableto:
1. Showthatwritingtounprotectedsharedglobalmemoryregioncanhave
undesirablesideeffectswhenaccessedbythreadsatthesametime.
2. Understandsharedglobalmemoryprotectionusingsynchronisedthreads.
3. Explainhowcriticalregionsofcodecanprotectsharedglobalmemoryareas.
4. Showthatmemoryareaslocaltothreadsareunaffectedbyotherthreads.

ProcessorandOSSimulators
Thecomputerarchitecturetutorialsaresupportedbysimulators,whichare
createdtounderpintheoreticalconceptsnormallycoveredduringthelectures.
Thesimulatorsprovidevisualandanimatedrepresentationofmechanisms
involvedandenablethestudentstoobservethehiddeninnerworkingsof
systems,whichwouldbedifficultorimpossibletodootherwise.Theadded
advantageofusingsimulatorsisthattheyallowthestudentstoexperimentand
exploredifferenttechnologicalaspectsofsystemswithouthavingtoinstalland
configuretherealsystems.

BasicTheory
Concurrentprocessesaccessingglobalsharedresourcesatthesametimecan
produceunpredictablesideeffectsiftheresourcesareunprotected.Computer
hardwareandoperatingsystemcanprovidesupportforimplementingcritical
regionsofcodewhengloballyaccessibleresourcesaresharedbyseveral
concurrentlyexecutingthreads.

Lab Exercises - Investigate and Explore


StarttheCPUsimulator.Younowneedtocreatesomeexecutablecodesothatitcanbe
runbytheCPUunderthecontroloftheOS.Inordertocreatethiscode,youneedtouse
thecompilerwhichispartofthesystemsimulator.Todothis,openthecompiler
windowbyselectingtheCOMPILERbuttoninthecurrentwindow.

1. Inthecompilerwindow,enterthefollowingsourcecodeinthecompilersource
editorarea(underPROGRAMSOURCEframetitle).Makesureyourprogramis
exactlythesameastheonebelow(besttousecopyandpasteforthis).
program CriticalRegion1
var g integer
sub thread1 as thread
writeln("In thread1")
g = 0
for n = 1 to 20
g = g + 1
next
writeln("thread1 g = ", g)
writeln("Exiting thread1")
end sub
sub thread2 as thread
writeln("In thread2")
g = 0
for n = 1 to 12
g = g + 1
next
writeln("thread2 g = ", g)
writeln("Exiting thread2")
end sub
writeln("In main")
call thread1
call thread2
wait
writeln("Exiting main")
end
TheabovecodecreatesamainprogramcalledCriticalRegion1.Thisprogram
createstwothreadsthread1andthread2.Eachthreadincrementsthevalueof
theglobalvariablegintwoseparateloops.
2

Workoutwhattwovaluesofgyouwouldexpecttobedisplayedontheconsole
whenthetwothreadsfinish?

Compilingandloadingtheabovecode:
i) CompiletheabovecodeusingtheCOMPILEbutton.
ii) LoadtheCPUinstructionsinmemoryusingtheLOADINMEMORYbutton.
iii) DisplaytheconsoleusingtheINPUT/OUTPUTbuttoninCPUsimulator.
iv) OntheconsolewindowchecktheStayontopcheckbox.

Runningtheabovecode:
i) EntertheOSsimulatorusingtheOS0buttoninCPUsimulator.
ii) Youshouldseeanentry,titledCriticalRegion1,inthePROGRAMLISTview.
iii) CreateaninstanceofthisprogramusingtheNEWPROCESSbutton.
iv) SelectRoundRobinoptionintheSCHEDULER/Policiesview.
v) Select10ticksfromthedropdownlistinRRTimeSliceframe.
vi) Makesuretheconsolewindowisdisplaying(seeabove).
vii) MovetheSpeedslidertothefastestposition.
viii) StarttheschedulerusingtheSTARTbutton.

Now,followtheinstructionsbelowwithoutanydeviations:
2. Whentheprogramstopsrunning,makeanoteofthetwodisplayedvaluesofg.Are
thesevalueswhatyouwereexpecting?Explainifthereareanydiscrepancies.

3. ChangeRRTimeSliceintheOSsimulatorwindowto5ticksandrepeattheabove
run.Again,makenoteofthetwovaluesofthevariableg.Arethesedifferentthan
thevaluesin(2)above?Ifso,explainwhy.

4. Modifythisprogramasshownbelow.Thechangesareinboldandunderlined.
RenametheprogramCriticalRegion2.
program CriticalRegion2
var g integer
sub thread1 as thread synchronise
writeln("In thread1")
g = 0
for n = 1 to 20
g = g + 1
next
writeln("thread1 g = ", g)
writeln("Exiting thread1")
end sub
sub thread2 as thread synchronise
writeln("In thread2")
g = 0
for n = 1 to 12
g = g + 1
next
writeln("thread2 g = ", g)
writeln("Exiting thread2")
end sub
writeln("In main")
call thread1
call thread2
wait
writeln("Exiting main")
end
NOTE:Thesynchronisekeywordmakessurethethread1andthread2codeare
executedmutuallyexclusively(i.e.notatthesametime).
5. Compiletheaboveprogramandloadinmemoryasbefore.Next,runitandcarefully
observehowthethreadsbehave.Makeanoteofthetwovaluesofvariableg.Are
theresultsdifferentthanthosein(2)and(3)above?Ifso,why?

6. Modifythisprogramforthesecondtime.Thenewadditionsareinboldand
underlined.Removethetwosynchronisekeywords.RenameitCriticalRegion3.
program CriticalRegion3
var g integer
sub thread1 as thread
writeln("In thread1")
enter
g = 0
for n = 1 to 20
g = g + 1
next
writeln("thread1 g = ", g)
leave
writeln("Exiting thread1")
end sub
sub thread2 as thread
writeln("In thread2")
enter
g = 0
for n = 1 to 12
g = g + 1
next
writeln("thread2 g = ", g)
leave
writeln("Exiting thread2")
end sub
writeln("In main")
call thread1
call thread2
wait
writeln("Exiting main")
end
NOTE:Theenterandleavekeywordpairprotecttheprogramcodebetween
them.Thismakessuretheprotectedcodeexecutesexclusivelywithoutsharing
theCPUwithanyotherthread.

7. LocatetheCPUassemblyinstructionsgeneratedfortheenterandleavekeywordsin
thecompilersPROGRAMCODEview.Youcandothisbyclickinginthesourceeditor

onanyoftheabovekeywords.CorrespondingCPUinstructionwillbehighlighted.
Makeanoteofthisinstructionhere:

8. Compiletheaboveprogramandloadinmemoryasbefore.Next,runit.Makeanote
ofthetwovaluesofvariableg.

9. Modifythisprogramforthethirdtime.Thenewadditionsareinboldand
underlined.Removetheglobalvariableg,enterandleavekeywords.Renameit
CriticalRegion4.
program CriticalRegion4
sub thread1 as thread
var g integer
writeln("In thread1")
g = 0
for n = 1 to 20
g = g + 1
next
writeln("thread1 g = ", g)
writeln("Exiting thread1")
end sub
sub thread2 as thread
var g integer
writeln("In thread2")
g = 0
for n = 1 to 12
g = g + 1
next
writeln("thread2 g = ", g)
writeln("Exiting thread2")
end sub
writeln("In main")
call thread1
call thread2
wait
writeln("Exiting main")
end

10. Compiletheaboveprogramandloadinmemoryasbefore.Next,runit.Makeanote
ofthetwovaluesofvariableg.Howdothenewgvariablesdifferthantheonesin
(1),(4)and(6)above?

11. Sowhathavewedonesofar?Tohelpunderstandtheorybettertrytoanswerthe
followingquestions.Youneedtoincludethisinyourportfolio,soitisimportantthat
youattemptallthequestionsbelow.However,youdontneedtocompletethispart
duringthetutorialsession.

a) Brieflyexplainthemainpurposeofthistutorialasyouunderstandit.
b) Whyhavewechosentodisplaythesameglobalvariableginboththreads?
c) Whatpopularhighlevellanguageusesthekeywordsynchronise(orsimilar)for
thesamepurposeasthecodein(4)?
d) Criticalregionsareoftenimplementedusingsemaphoresandmutexes.Findout
whattheseareandhowtheydiffer.Describeonaseparatesheet.
e) SomecomputerarchitectureshaveatestandsetCPUinstructionfor
implementingcriticalregions.Findouthowthisworksandbrieflydescribeona
separatesheet.
f) Intheabsenceofanyhelpfromhardwareandoperatingsystem,howwouldyou
protectacriticalregioninyourcode?Suggestawayofdoingitandstatehowit
woulddifferfromtheabovemethods(hint:busywait).

You might also like