-
Notifications
You must be signed in to change notification settings - Fork 1
/
chapter06.html
2687 lines (2082 loc) · 76 KB
/
chapter06.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Process Synchronization</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="css/slides.css" rel="stylesheet" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, title-slide
## CSCI 340 Operating Systems
<br>
## Chapter 6: Process Synchronization
.author[
Stewart Weiss<br>
]
.license[
Copyright 2020 Stewart Weiss. Unless noted otherwise all content is released under a
[Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
]
---
name: cc-notice
template: default
layout: true
.bottom-left[© Stewart Weiss. CC-BY-SA.]
---
name: tinted-slide
template: cc-notice
layout: true
class: tinted
---
name:toc
### Table of Contents
[Prerequisite Reading](#prereqs)<br>
[Terminology](#terminology)<br>
[About This Chapter](#about-chapter)<br>
[Chapter Objectives](#objectives)<br>
[The Basic Problem](#the-problem)<br>
[Synchronization Mechanisms](#synchronization)<br>
[Why is this an Operating System Topic?](#reason-we-study-synch)<br>
[Example of a Race Condition](#race-cond-example)<br>
[Producer and Consumer Code](#prod-cons-code)<br>
[The Race Condition](#race-in-prod-cons)<br>
[Race Conditions in the Kernel](#kernel-races)<br>
[Preventing Race Conditions in the Kernel](#preventing-races)<br>
[Preemptive Kernels](#preemptive-kernels)<br>
[Re-entrant Kernels](#reentrant-kernels)<br>
[Preventing Race Conditions: The Critical Section Problem](#cs-problem)<br>
[General Form of a Process](#process-form)<br>
[The Conditions A Solution Must Satisfy](#cs-conditions)<br>
[Allowed Assumptions](#assumptions)<br>
[Algorithm 1](#algorithm-1)<br>
[Algorithm 1](#algorithm-1-2)<br>
[Satisfies Mutual Exclusion?](#alg1-mutex)<br>
---
### Table of Contents
[Satisfies Progress?](#alg1-progress)<br>
[Algorithm 2](#algorithm-2)<br>
[Satisfies Mutual Exclusion?](#alg2-mutex)<br>
[Satisfies Progress?](#alg2-progress)<br>
[Peterson's Two-Process Software Solution](#peterson-solution)<br>
[Peterson's Algorithm](#peterson-alg)<br>
[Satisfies Mutual Exclusion?](#peterson-mutex)<br>
[Satisfies Progress?](#peterson-progress)<br>
[Satisfies Bounded Waiting?](#peterson-bound-wait)<br>
[Limitations of Peterson's Algorithm](#peterson-limits)<br>
[Effects of Instruction Re-ordering](#instruct-reorder)<br>
[Effects of Instruction Re-ordering (2)](#instruct-reorder-effects)<br>
[Peterson's Algorithm Re-ordered](#peterson-reordered)<br>
[Memory Barriers](#memory-barriers)<br>
[Memory Models](#memory-models)<br>
[Example](#mem-barrier-example)<br>
[Peterson's Revisited](#peterson-revisited)<br>
[Hardware Support for Critical Section Solutions](#hardware-support)<br>
[Bus locking](#bus-locking)<br>
[Hardware Primitives](#hardware-primitives)<br>
[The Test-and-Set Instruction](#test-and-set)<br>
[Implementing Test-and-Set](#test-and-set-implementation)<br>
[Using Test-and-Set for Critical Sections](#testset-cs)<br>
---
### Table of Contents
[Compare-and-Swap Instruction](#cas)<br>
[Implementing Test-and-Set With Compare-and-Swap](#cas-as-tas)<br>
[Using Compare-and-Swap for Critical Sections](#cas-cs)<br>
[Spinlocks](#spinlocks)<br>
[Ensuring Bounded Waiting Using Locks](#cs-bounded-waiting)<br>
[Why This Works](#cs-bounded-wait2)<br>
[Atomic Variables](#atomic-vars)<br>
[Implementing Atomic Variables](#atomic-vars-2)<br>
[Implementing Atomic Increment](#atomic-inc)<br>
[Mutex Locks](#mutex-locks)<br>
[Mutex Lock Semantics](#mutex-lock-semantics)<br>
[Using Mutex Locks for Critical Sections](#using-mutex-lock)<br>
[Semaphore Origins](#sem-origins)<br>
[Semaphore Definition](#sem-def)<br>
[Observations](#sem-observations-1)<br>
[Observations](#sem-observations-2)<br>
[Binary Semaphores for Mutual Exclusion](#sem-cs)<br>
[Bounded Waiting and Semaphores](#sem-cs-bounded-waiting)<br>
[Counting Semaphores](#counting-sems)<br>
[Example](#counting-sem-example)<br>
[Semaphores for Serializing](#sem-synching)<br>
[Implementing Semaphores: Considerations](#sem-implementation)<br>
[Semaphore Implementation](#sem-implementation-2)<br>
---
### Table of Contents
[Implementing .fixedblue[wait()]](#wait-implementation)<br>
[Implementing .fixedblue[signal()]](#signal-implementation)<br>
[Liveness](#liveness)<br>
[Deadlock](#liveness-deadlock)<br>
[Priority Inversion](#liveness-priority-inversion)<br>
[Priority Inheritance Protocol](#priority-inheritance)<br>
[References](#references)<br>
<!--TOC_END-->
---
name: prereqs
### Prerequisite Reading
Before reading these slides, you should be familiar with material
from the following topics, best achieved by reading the indicated
chapters from these lecture notes.
- Computer organization ([Chapter 1](chapter01.html))
- Operating system structure ([Chapter 2](chapter02.html))
- Processes and concurrency ([Chapter 3](chapter03.html))
---
name: terminology
### Terminology
In this slide set, we use the terms "process" and "thread" interchangeably,
because the processes that we consider are all single-threaded.
The reader should be aware that unrelated processes generally are not able
to access shared variables, whereas threads generally can.
In the slides, when we refer to processes that access shared variables, the
reader can think of these as either threads, or as processes that have set up
shared memory through an appropriate kernel API.
Lastly, processes and threads _are not_ generally the same thing. We would
use the term "task", as Linux does, to mean a process or a thread, but most
people do not use "task" in this way and we do not want to muddy the waters
even further. If we need to say something about processes that is not true of threads,
or vice versa, we shall explicitly say so.
---
name: about-chapter
### About This Chapter
This chapter covers problems related to concurrent execution of processes
and methods of solving those problems.
The general topics that it explores are:
.lightbluebox[
- The Basic Problem
- The Critical-Section Problem
- Software Solution: Peterson’s Solution
- Hardware Support for Synchronization
- Mutex Locks
- Semaphores
- Liveness
]
---
name: objectives
### Chapter Objectives
Having read and understood the content of this chapter, you should be able to
- describe the critical-section problem and give an example of a race condition;
--
- describe various software solutions to the problem and explain their limitations;
--
- describe hardware solutions to the critical-section problem using
memory barriers, compare-and-swap operations, test-and-set, and atomic variables;
--
- demonstrate how mutex locks and semaphores can be used to solve the critical section problem;
--
- describe various liveness properties and be able to determine whether concurrent
process systems have those properties.
---
name: the-problem
### The Basic Problem
.big[What problem are we trying to solve?]
- Processes can execute concurrently, either on same processor or on different ones.
- Processes may be interrupted at any time, partially completing execution.
- Processes might modify shared data.
- Concurrent modification of shared data may result in .bluebold[data inconsistency]:
when two or more processes have different values of the same data object,
such as a shared counter.
- When the data inconsistency depends on the _order_ in which the processes
modify the shared data, _and this is undesirable_, it is called a .bluebold[race condition].
- Preventing race conditions requires .redbold[synchronization mechanisms] to ensure the controlled
execution of cooperating processes.
---
name: synchronization
### Synchronization Mechanisms
People use the term “synchronization” to mean making two things happen at the
same time.
--
In computer science, .bluebold[synchronization] is the control of the order
of events in time.
.bluebold[Synchronization constraints] are requirements that are imposed on
a set of events with respect to when they occur in time.
- .bluebold[Mutual Exclusion]: Two events A and B .redbold[cannot] occur at the
exact same time.
- .bluebold[Serialization]: Event A must occur before event B.
.bluebold[Synchronization mechanisms] are methods used to enforce synchronization, whether
in hardware, software, or a combination of both.
---
name: reason-we-study-synch
### Why is this an Operating System Topic?
Modern operating systems are composed of cooperating processes and/or threads.
- These modify and access shared data such as tables that control memory allocation,
file access, process creation, device management, and so on.
- These accesses are potential race conditions that must be resolved.
--
Therefore to understand operating system design and function,
it is imperative to understand the different means of process synchronization with
respect to shared resources.
---
name: race-cond-example
### Example of a Race Condition
- The solution to the .redbold[producer-consumer problem] from Chapter 3
needed to keep one buffer empty to distinguish between empty and full conditions in the buffer pool:
.center[
```
in == out iff buffer is empty
(in +1) % BUFFER_SIZE == out iff buffer is full
```
]
.center[
<img src="figures/bufferpool.png" width=60% alt="Buffer Pool"/>
]
- Suppose that we want a solution that fills _all of the buffers_.
--
- We can keep an integer .fixedblue[counter] that keeps track of the number of
full buffers. Initially, .fixedblue[counter == 0].
- It is incremented by the producer after it fills a buffer and is
decremented by the consumer after it consumes (empties) a buffer.
---
name: prod-cons-code
### Producer and Consumer Code
.centered_80[
Producer:
```C
while (true) {
/* produce an item in next produced */
while (counter == BUFFER_SIZE)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
`counter++;`
}
```
]
.centered_80[
Consumer:
```C
while (true) {
while (counter == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
`counter--;`
/* consume the item in next consumed */
}
```
]
---
name: race-in-prod-cons
### The Race Condition
- This code has a .redbold[race condition] on the .fixedblue[counter] variable. In the two highlighted
lines
- .fixedblue[counter++] could be implemented with three machine instructions equivalent to
```
register1 = counter
register1 = register1 + 1
counter = register1
```
- .fixedblue[counter--] could be implemented with three machine instructions equivalent to
```
register2 = counter
register2 = register2 - 1
counter = register2
```
- Consider the execution sequence with .fixedblue[counter == 2] initially. .fixedblue[tk] denotes
the kth time step:
```
t0: producer executes register1 = counter {register1 == 2 }
t1: producer executes register1 = register1 + 1 {register1 == 3 }
t2: consumer executes register2 = counter {register2 == 2 }
t3: consumer executes register2 = register2 – 1 {register2 == 1 }
t4: producer executes counter = register1 {counter == 3 }
t5: consumer executes counter = register2 {counter == 1 }
```
- If t4 and t5 are swapped, then the final value of .fixedblue[counter] is 3, not 1.
---
name: kernel-races
### Race Conditions in the Kernel
- Race conditions can occur whenever shared variables are updated by two independent
processes or threads.
- A Linux kernel would have many race conditions if it did not use
mechanisms to prevent them. For example,
- In the implementation of the .fixedblue[fork()] system call, a new process id is assigned
to the newly created process.
- This requires incrementing the variable that stores the next available process id value.
- If a computer has multiple cores, two processes might try to update that
variable concurrently. On a single core, if the kernel is interrupted in the
middle of the update, it is also possible that a second process could try to
update it as well.
- The value of the next available pid could be corrupted if these accesses were
not synchronized.
---
template: tinted-slide
layout: true
---
name: preventing-races
### Preventing Race Conditions in the Kernel
- On a single-core processor, the kernel could use the following strategy:
```
disable all interrupts before executing any updates;
perform the updates;
re-enable interrupts
```
- This would guarantee that only one process at a time could modify shared data.
- On multiprocessors, this does not suffice, because the shared data can be
modified by two different processes on separate cores.
- Even on a single-processor machine with no hyper-threading, disabling interrupts
is not an efficient solution for long sections of code, since important events
might need to be handled during the period for which interrupts are disabled.
---
name: preemptive-kernels
### Preemptive Kernels
- A kernel is defined to be .redbold[preemptive] if it allows a process that is executing
code in it to be preempted. In effect, more than one process can be executing
kernel code, even the same code, concurrently.
- A kernel that does not allow this is called a .redbold[non-preemptive kernel].
In a non-preemptive kernel, a kernel-mode process will run until it exits
kernel mode, blocks, or voluntarily yields control of the CPU.
- Non-preemptive kernels are simpler to design but have poorer response time
than premptive kernels.
---
name: reentrant-kernels
### Re-entrant Kernels
- A kernel is defined to be .redbold[re-entrant] if more than one process can safely
execute its code concurrently, meaning without causing data inconsistency.
This means that more than one process executes in __kernel mode__ at a time.
- Preemptive kernels must be re-entrant, otherwise data inconsistency results.
- How can kernel code be made re-entrant?
--
- If all kernel functions modify only local variables and do not alter
global data structures, the code is re-entrant.
Such functions are called .redbold[re-entrant functions].
- Alternatively, if the kernel functions modify shared data structures, then some other kind of
mechanism is needed to ensure that race conditions do not occur.
This is what we are about to study.
---
name: cs-problem
### Preventing Race Conditions: The Critical Section Problem
- Consider a system of n concurrent processes P.sub[0], P.sub[1], ...,P.sub[n-1].
- Each process has a .redbold[critical section] of code in which:
- it may be modifying shared variables, updating tables, writing files, etc.
- requiring that, when one process is in its critical section, no other can be in its critical section.
- The .redbold[Critical Section Problem] is to design a protocol that all processes
can use to coordinate their accesses to this critical section of code.
- A solution requires that each process must
1. ask permission to enter its critical section in an .redbold[entry section],
1. execute the .redbold[critical section]
1. execute an .redbold[exit section] in which it indicates that it
exited its critical section, and
1. execute .redbold[non-critical section] code.
---
name: process-form
### General Form of a Process
- Since the goal is to find protocols to solve the critical section problem, we represent
a process as doing nothing but repeatedly entering and exiting a critical section,
and doing "other stuff" when it is not in its critical section.
- Therefore we represent a process as executing code of the following form:
.centered_80[
```
loop forever {
ENTRY SECTION : indicate wish to enter the critical section
Critical Section (CS)
EXIT SECTION: indicate leaving the critical section
Non-Critical Section (NCS)
}
```
]
---
name: cs-conditions
### The Conditions A Solution Must Satisfy
.section[
.bigger[Any solution to the problem must satisfy three criteria.]
- .redbold[Mutual Exclusion]. If a process is executing in its critical section,
then no other processes can be executing in their critical sections.
- .redbold[Progress]. If no process is executing in its critical section and there exist
some processes that wish to enter their critical section,
then the selection of the processes that will enter the critical
section next cannot be postponed indefinitely.
- .redbold[Bounded Waiting]. A bound must exist on the number of times
that other processes are allowed to enter their critical sections
after a process has made a request to enter its critical section
and before that request is granted.
]
---
name: assumptions
### Allowed Assumptions
.section[
.bigger[ What can we assume?]
- We can assume that each process executes at a nonzero speed.
- We can assume that machine instructions to fetch, store, and test values are
.bluebold[atomic], i.e., uninterruptible.
- We can assume processes do not halt in their critical sections.
- We .bluebold[cannot assume] that processes execute at any particular relative speeds
or that some processes have higher priorities than others.
]
---
template: default
layout: true
---
name: software-solutions
class: center, middle, inverse
## Software Solutions
We examine solutions to the critical section
problem that do not require any special hardware.
---
template: tinted-slide
layout: true
---
name: algorithm-1
### Algorithm 1
Assume that two processes, .fixedblue[P0] and .fixedblue[P1], execute concurrently. They share a
variable .fixedblue[turn] set to 0 initially:
```C
turn = 0;
```
.left-column[.left[.smaller[
```C
P0:
while (true) {
while (turn != 0) {} /* entry section*/
/* critical section (CS) */
turn = 1; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
while (turn != 1) {} /* entry section*/
/* critical section (CS)*/
turn = 0; /* exit section */
/* remainder section (NCS) */
}
```
]]]
- Process P.sub[k]'s (`k=0,1`) entry section is essentially of the form
.redbold[.fixed[ wait until turn == k]].
- Process P.sub[k]'s (`k=0,1`) exit section is essentially of the form
.redbold[.fixed[turn = 1-k; ]].
(i.e., other process gets turn)
- Implies P.sub[k] is in CS only if .fixedblue[turn == k].
- Once P.sub[k] leaves CS, it modifies .fixedblue[turn] so the other process can enter.
- Processes therefore .greenbold[take turns] in CS. (This is called .bluebold[ alternation. ])
---
name: algorithm-1-2
### Algorithm 1
Assume that two processes, .fixedblue[P0] and .fixedblue[P1], execute concurrently. They share a
variable .fixedblue[turn] set to 0 initially:
```C
turn = 0;
```
.left-column[.left[.smaller[
```C
P0:
while (true) {
while (turn != 0) {} /* entry section*/
/* critical section (CS) */
turn = 1; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
while (turn != 1) {} /* entry section*/
/* critical section (CS)*/
turn = 0; /* exit section */
/* remainder section (NCS) */
}
```
]]]
- Loops such as .fixedblue[while (turn != 1)] are called .bluebold[busy-waiting] loops.
The process that executes them is very busy doing nothing other than testing
the value of a variable, waiting for it to become a specific value.
- They are not very efficient in terms of CPU cycles. Later we see
alternative solutions.
--
- Still, does this satisfy mutual exclusion, progress, and bounded waiting?
---
name: alg1-mutex
### Satisfies Mutual Exclusion?
.left-column[.left[.smaller[
```C
P0:
while (true) {
while (turn != 0) {} /* entry section*/
/* critical section (CS) */
turn = 1; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
while (turn != 1) {} /* entry section*/
/* critical section (CS)*/
turn = 0; /* exit section */
/* remainder section (NCS) */
}
```
]]]
- Yes.
--
- The variable .fixedblue[turn] is shared.
It can store either a .fixedblue[1] or a .fixedblue[0] at any
time, not both.
- Since .fixedblue[P0] is in CS only if .redbold[ .fixed[turn == 0]] and
.fixedblue[P1] is in CS only if .redbold[ .fixed[turn == 1]],
they cannot be in the CS at the same time.
---
name: alg1-progress
### Satisfies Progress?
.left-column[.left[.smaller[
```C
P0:
while (true) {
while (turn != 0) {} /* entry section*/
/* critical section (CS) */
turn = 1; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
while (turn != 1) {} /* entry section*/
/* critical section (CS)*/
turn = 0; /* exit section */
/* remainder section (NCS) */
}
```
]]]
--
- Consider this sequence:
.fixedblue[P0] enters CS, sets .fixedblue[turn] to 1, enters NCS and stays there a long time.
.fixedblue[P1] enters CS because .fixedblue[turn] is 1, sets .fixedblue[turn] to 0, enters its NCS, goes back to
its entry section and waits for .fixedblue[turn] to become 1.
But .fixedblue[turn] cannot become 1 until .fixedblue[P0] leaves its NCS, enters its CS again.
- Progress is not satisfied because a process that wants to enters its CS (.fixedblue[P1]) is blocked from
getting in even though no other process is in its entry or exit sections or its
CS.
---
name: algorithm-2
### Algorithm 2
- Assume two processes, .fixedblue[P0] and .fixedblue[P1], execute concurrently
- __Initialization__. A global array of two bools, initially both .fixedblue[false]:
```
bool flag[2] = {false, false};
```
- The variable .redbold[ .fixedblue[flag]] should be named
.redbold[.fixedblue[ready_to_enter_CS]] for clarity.
.left-column[.left[.smaller[
```C
P0:
while (true) {
flag[0] = true; /* entry */
while ( flag[1] ) {} /* section */
/* critical section (CS) */
flag[0] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
flag[1] = true; /* entry */
while ( flag[0] ) {} /* section */
/* critical section (CS) */
flag[1] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
- When process P.sub[k] (`k=0,1`) sets .fixedblue[flag[k] = true],
it is saying, "I am ready to enter CS".
- It then politely waits for other process with the following .fixedblue[while] loop -
if other process is ready to enter its CS, it waits.
---
name: alg2-mutex
### Satisfies Mutual Exclusion?
.left-column[.left[.smaller[
```C
P0:
while (true) {
flag[0] = true; /* entry */
while ( flag[1] ) {} /* section */
/* critical section (CS) */
flag[0] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
flag[1] = true; /* entry */
while ( flag[0] ) {} /* section */
/* critical section (CS) */
flag[1] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
- Yes.
--
- A process enters its CS only if the other process is NOT ready to enter,
e.g., process .fixedblue[P0] enters CS only if .fixedblue[flag[1]] is .fixedblue[false]. Both processes set
their .fixedblue[flag] to true before testing each other's .fixedblue[flag] so both cannot be
.fixedblue[false] at the top of the loop on each iteration.
---
name: alg2-progress
### Satisfies Progress?
.left-column[.left[.smaller[
```C
P0:
while (true) {
flag[0] = true; /* entry */
while ( flag[1] ) {} /* section */
/* critical section (CS) */
flag[0] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
flag[1] = true; /* entry */
while ( flag[0] ) {} /* section */
/* critical section (CS) */
flag[1] = false; /* exit section */
/* remainder section (NCS)*/
}
```
]]]
--
- Consider this scenario:
- .fixedblue[P0] sets .fixedblue[flag[0] = true] and .fixedblue[P1] sets .fixedblue[flag[1] = true] at the same time.
- Each now executes its respective while loop.
- Because both are ready to enter CS, neither while loop is exited and both
processes wait forever to enter the CS.
--
- No progress is made.
--
- This is called .redbold[deadlock].
---
name: peterson-solution
### Peterson's Two-Process Software Solution
- Gary Peterson invented it in 1981<span class="super">1</span>.
- This algorithm uses both variables, .fixedblue[flag[2]] and .fixedblue[turn] to solve the problem.
- The use of both prevents alternation and prevents deadlock.
- It assumes that the load and store machine-language instructions are atomic;
that is, cannot be interrupted.
- The variable .fixedblue[turn] indicates whose turn it is to enter the critical section.
- The .fixedblue[flag] array is used to indicate if a process is ready to enter the critical section.
.fixedblue[flag[k] = true] implies that process P.sub[k] is ready.
.footnote[
[1] G. L. Peterson: "Myths About the Mutual Exclusion Problem", Information Processing Letters 12(3) 1981, 115–116
]
---
name: peterson-alg
### Peterson's Algorithm
- A process gains entry to its CS if the other process is not ready to enter its CS
(by setting its .fixedblue[flag] to false) __or__ if the other process has given
privilege to the process by setting .fixedblue[turn] to that process's id, e.g., .fixedblue[turn = 0].
- __Initialization__.
```C
bool flag[2] = {false, false};
int turn;
```
.left-column[.left[.smaller[
```C
P0:
while (true) {
flag[0] = true;
turn = 1;
while (flag[1] == true && turn == 1) {}
/* critical section (CS) */
flag[0] = false;
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
flag[1] = true;
turn = 0;
while (flag[0] == true && turn == 0) {}
/* critical section (CS) */
flag[1] = false;
/* remainder section (NCS)*/
}
```
]]]
---
name: peterson-mutex
### Satisfies Mutual Exclusion?
.left-column[.left[.smaller[
```C
P0:
while (true) {
flag[0] = true;
turn = 1;
while (flag[1] == true && turn == 1) {}
/* critical section (CS) */
flag[0] = false;
/* remainder section (NCS)*/
}
```
]]]
.right-column[.left[.smaller[
```C
P1:
while (true) {
flag[1] = true;
turn = 0;
while (flag[0] == true && turn == 0) {}
/* critical section (CS) */
flag[1] = false;
/* remainder section (NCS)*/
}
```
]]]
- If .fixedblue[P0] is in its CS, then it set .fixedblue[flag[0]] to true. (Only sets it to false
when it leaves, and then it gets set to true again after the NCS.)
- The same is true of .fixedblue[P1]: if .fixedblue[P1] is in its CS, it set .fixedblue[flag[1]] to true and has not yet
set it to false again. Therefore, if both are in their CS, then
.fixedblue[flag[0] == flag[1] == true].
--
- To enter its CS, when .fixedblue[P0] evaluated its condition either .fixedblue[flag[1] == false] or .fixedblue[turn == 0].