0% found this document useful (0 votes)
718 views7 pages

Investigating Synchronisation

This document describes a lab exercise on investigating thread synchronization. The exercise involves writing programs with multiple threads that increment a shared global variable. By observing the output values of the variable for different implementations, students can learn about issues that arise from concurrent access to shared resources, and ways to synchronize threads using language keywords, operating system calls, and CPU instructions to properly implement critical regions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
718 views7 pages

Investigating Synchronisation

This document describes a lab exercise on investigating thread synchronization. The exercise involves writing programs with multiple threads that increment a shared global variable. By observing the output values of the variable for different implementations, students can learn about issues that arise from concurrent access to shared resources, and ways to synchronize threads using language keywords, operating system calls, and CPU instructions to properly implement critical regions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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