-
Notifications
You must be signed in to change notification settings - Fork 1
/
chapter04.html
2381 lines (1688 loc) · 73.2 KB
/
chapter04.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>Threads</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 4: Threads
.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/).
Background image: roof of the EPIC Museum, Dublin, by Stewart Weiss.
]
---
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
[Prologue: Processes Revisited](#prologue-1)<br>
[Prologue: Threads](#prologue-2)<br>
[About This Chapter](#about-chapter)<br>
[Chapter Objectives](#objectives)<br>
[Motivation](#more-motivation)<br>
[What is a Thread?](#thread-posix-def)<br>
[Thread Resources](#thread-resources)<br>
[Single- and Multi-Threaded Processes](#thread-visualization)<br>
[Visualizing Threads](#thread-symbol)<br>
[Reasons for Multi-threading](#thread-uses)<br>
[Concurrency Versus Parallelism](#concurrency)<br>
[Visualizing Concurrency and Parallelism](#concurrency-visualized)<br>
[Challenges in Parallel Programming](#parallel-challenges)<br>
[Sources of Parallelism in Problems](#parallelism-models)<br>
[Visual Comparison](#parallelism-visualized)<br>
[Speed-Up](#speedup)<br>
[Limitations of Parallelization](#speed-up-limits)<br>
[Amdahl's Law](#amdahls-law)<br>
[Applications of Amdahl's Law](#amdahl-examples)<br>
[Maximum Possible Speedup](#amdahl-limit)<br>
[Plot of Amdahl's Law](#amdahl-plot)<br>
---
### Table of Contents
[Multi-threading Models](#multithreading-models)<br>
[Thread Implementations](#thread-types)<br>
[User Level Threads](#user-threads-1)<br>
[A POSIX Threads Example](#pthreads-example-1)<br>
[Some Explanation](#pthreads-2)<br>
[Fork-Join Flow](#fork-join-2)<br>
[User Level Threads: Pros](#user-threads-pros)<br>
[User Level Threads: Cons](#user-threads-cons)<br>
[Kernel Level Threads](#kernel-level-threads-1)<br>
[Kernel Level Threads: The Confusion](#kernel-level-threads-2)<br>
[Kernel Level Threads: A Visualization](#kernel-level-threads-3)<br>
[About Kernel Level Threads in Linux](#linux-kernel-level-threads)<br>
[Linux Kernel Level Thread Example](#kthread-example-2)<br>
[Linux Kernel Level Thread Example](#kthread-example-info)<br>
[Kernel Level Threads: Pros and Cons](#kernel-threads-2)<br>
[Implementation of User Level Threads](#user-thread-models)<br>
[Many-to-One (M:1) Threading Model](#many-to-one)<br>
[Many-to-One (M:1) Threading Model Pros and Cons](#many-to-one-2)<br>
[One-to-One (1:1) Threading Model](#one-to-one)<br>
[One-to-One (1:1) Threading Model Pros and Cons](#one-to-one-2)<br>
[Many-to-Many (M:N) Threading Model](#many-to-many)<br>
[Many-to-Many (M:N) Threading Model Pros and Cons](#many-to-many-2)<br>
[Two-Level Threading Model](#two-level)<br>
---
### Table of Contents
[Scheduler Activations](#scheduler-activations)<br>
[Scheduler Activation Use](#scheduler-activations-2)<br>
[Implicit Threading](#implicit-threading-intro)<br>
[Parallelizing Compilers](#parallelizing-compilers)<br>
[Types of Implicit Threading](#implicit-thread-types)<br>
[Underlying Technology](#technologies)<br>
[Thread Pools](#thread-pools)<br>
[The Fork-Join Model](#fork-join-1)<br>
[Fork-Join Parallelism](#fork-join-2)<br>
[OpenMP Overview](#openmp-intro)<br>
[OpenMP Key Features](#openmp-features-1)<br>
[OpenMP Run-time Routines](#openmp-features-2)<br>
[OpenMP Example Program](#openmp-example)<br>
[Grand Central Dispatch](#grand-central-dispatch)<br>
[Example of a GCD Program](#gcd-example)<br>
[Issues with .fixedblue[fork()]](#fork-issues)<br>
[Issues with the .fixedblue[exec()] Family](#exec-issues)<br>
[Signals](#signals)<br>
[Signal Handling](#signal-handling)<br>
[Signals and Threads: Issues](#signal-handling-questions)<br>
[Signals and Threads: Solutions](#signal-handling-threads)<br>
[Thread Cancellation](#thread-cancellation)<br>
[Thread Cancelability](#thread-cancellation-issues)<br>
---
### Table of Contents
[Thread Cancelability Control](#thread-cancelability)<br>
[Thread Cancellation Points](#thread-cancellation-points)<br>
[References](#references)<br>
<!--TOC_END-->
---
name: prologue-1
### Prologue: Processes Revisited
In the preceding chapter, you learned about .greenbold[processes].
A process was defined as a program in execution, and it was assumed that
a process had a single .greenbold[thread of control].
What does this mean?
--
- A ".bluebold[thread of control]" is a .redbold[sequence] of instructions that is
executed .redbold[one instruction at a time], .redbold[one after the other],
during the execution of a program.super[1].
.left-column[
Imagine that when a program executes, each time a machine code instruction is executed,
the time of execution and address of the machine code instruction are written to a line of output.
A single thread of control through a program would generate a graph such as the one to
the right.
]
.right-column[
<img src="figures/thread-path.png" width=100% alt="thread">
]
--
.below-column[
.redbold[Food for thought]: Why does this graph have repeating patterns, and why does it make big jumps?
]
---
name: prologue-2
### Prologue: Threads
Modern operating systems have made it possible for a process to have
.greenbold[multiple threads of control]. These multiple threads of control are
called .greenbold[threads].
--
.left-column[
Multiple threads of a process can run .redbold[in parallel] and can therefore
speed up a computation, taking advantage of the multiple processors that
exist in almost all modern computers.
To the right is a graph of two threads of a multithreaded program.
]
.right-column[
<img src="figures/thread-paths-2.png" width=100% alt="parallel threads">
]
--
.below-column[
Some programs can have hundreds or even thousands of threads.
.redbold[Modern operating system kernels are always multithreaded.]
]
---
name: about-chapter
### About This Chapter
Because threads are so ubiquitous and also so hard to understand, they
are an important topic in an operating systems course, and this chapter
is entirely devoted to their study. In particular, it will
cover the following topics:
- Multicore programming
- Explicit Threading
- Thread libraries
- Implicit threading
- Threading issues
---
name: objectives
### Chapter Objectives
You should be able to
- identify the basic components of a thread, and compare and contrast
threads and processes;
--
- describe the advantages and disadvantages of designing multithreaded
programs as compared to single-threaded programs;
--
- explain and apply .greenbold[Amdahl's Law];
--
- describe various multithreading models, explain how they differ, and
identify the strengths and weaknesses of each model;
--
- explain what a thread library is and name three different thread libraries;
--
- read, understand, and modify simple programs that use the .greenbold[Pthreads] library;
--
- explain what implicit threading is and describe .greenbold[thread pools],
the .greenbold[fork-join model], and .greenbold[OpenMP];
--
- describe how the Linux operating system represents threads; and
--
- read and understand simple multithreaded programs that use the Linux threading API.
---
name: more-motivation
### Motivation
.redbold[Why are threads an important topic?]
--
- Modern kernels are multithreaded. Understanding them requires understanding threads.
--
- Most modern applications are multithreaded. Examples:
- A web browser process might have one thread to render images and text
and another to download data.
- A web browser might run each plug-in in a separate thread.
- A chess program might have one thread "listening" for user input and rendering the
chess board, and another analyzing future moves, while the user is thinking.
--
- Creating processes is much more time-consuming than creating threads.
- Processes use many more resources than threads overall.
--
- Because threads share many of the same resources, cooperation among the threads
that share resources .redbold[can] be easier.
--
- .redbold[But multithreading a program is difficult and dangerous and requires great understanding.]
.redbold[Hence it is important to understand how to use threads.]
---
name: thread-posix-def
### What is a Thread?
We have been discussing threads as an abstraction until now, so it is time
to ask, what exactly is a thread?
--
While there is no single definition, the one most commonly used is the one
stated by POSIX:
> _A .bluebold[thread] is the set of all resources necessary_
> _to represent a single thread of control through a program's executable code._
This is the definition implicit in the Silberschatz, Gagne, Galvin textbook.
--
From this definition, it follows that a thread has resources. In particular,
because it executes instructions, it needs access to an address space
containing executable code, usually the address space of a parent process.
It also follows that a thread is part of a process: processes contain threads
and threads do not "live outside of processes."
--
.redbold[We will use this definition of threads for now, but will present an alternative definition later.]
---
name: thread-resources
### Thread Resources
When a process has multiple threads, the question is,
.redbold[which resources are unique to each thread and which are shared by all threads?]
--
Each thread within that process .redbold[has its own]:
- unique thread ID
- program counter (PC)
- register set
- user stack
In some implementations, other resources such as signal masks are thread-specific.
--
All threads .redbold[share] many process resources, but the most important are:
- the executable code, i.e., the .greenbold[text segment],
- the .greenbold[heap] memory, where dynamically allocated data is stored,
- the .greenbold[data segments], containing initialized and uninitialized data,
- the .greenbold[command line arguments], .greenbold[environment variables], and .greenbold[open files].
---
name: thread-visualization
### Single- and Multi-Threaded Processes
We can visualize single-threaded and multithreaded processes as shown below:
.left-column[
.center[ Single-threaded Process]
<img src="figures/single-threaded.png" width=90% alt="single-threaded process">
]
.right-column[
.center[ Multi-threaded Process]
<img src="figures/multithreaded.png" width=90% alt="multithreaded process">
]
--
.below-column[
Notice that, in the multithreaded process to the right, each thread's
stack, registers, and program counter are no longer process resources, but
.redbold[thread-private] resources.
]
---
name: thread-symbol
### Visualizing Threads
.left-column-large[
In the preceding illustration of a multithreaded process, there were four threads,
each of which was represented by the abstract figure to the right.
In this figure, the curved line represents the thread of control through the
set of instructions executed by the thread.
]
.right-column-small[
<img src="figures/thread-rep.png" width=50% alt="thread representation">
]
--
An individual thread is often depicted in a simpler way,
eliminating the hardware resources, and just depicting it as just the squiggly
flow of control:
<img src="figures/thread_magenta.png" width=20% alt="thread">
We use this convention in the remainder of the notes.
---
template: tinted-slide
layout: true
---
name: thread-counting-activity
count: false
class: breakout
### A Thread Counting Activity
How many threads does a process have? How can you tell?
--
In a few ways. In this activity you will count threads in one
particular way.
Login to .fixedblue[eniac.cs.hunter.cuny.edu].
Then run the following command:
```bash
ps -efwL | more
```
You will see a list of all running processes on .fixedblue[eniac], including their
threads, one screenful at a time. (To advance to the next screen, press the .fixedblue[space] bar;
to exit the command, type ".fixedblue[q]".) The last field on the line is the
command that was executed to create the process (or thread).
The 6.super[th] field (with heading .fixedblue[NLWP]) is the number of threads that the given process has.
A process with the value 1 in this column has one thread and is thus not multithreaded.
Which process has the most threads? What is the command that created it?
How many threads does .fixedblue[gnome-shell] have?
---
name: thread-uses
### Reasons for Multi-threading
There are several good reasons to write programs that can contain multiple
threads.
- Code to handle .greenbold[asynchronous.super[1] events] can be executed by a separate thread.
Each thread can handle its own event without using some type of asynchronous
programming construct.
.footnote[
1 Asynchronous events are events that take place independently of the execution of
the program, such as completion of an I/O operation, or the termination of a
child process.
]
--
- Whereas multiple processes have to use special mechanisms provided by the kernel
to share memory and file descriptors, threads automatically have access
to the same memory address space, which is faster and simpler.
--
- On a multiprocessor architecture, many threads may run in parallel on separate
cores, speeding up the computation. More cores can make the program faster.
--
- Even on a single processor machine, performance can be improved by putting
calls to system functions with expected long waits into separate threads.
This way, just the calling thread waits, not the whole process.
--
- The response time of interactive programs can be improved by splitting off
threads to handle user I/O. By handling I/O in separate threads, the
application can respond quickly, even when time-consuming operations are taking place in
other threads.
---
name: multicore-programming
layout: false
class: center, middle, inverse
## Multicore Programming
We explore how programs can be written that take advantage of the multiple cores
and/or processors in a multiprocessor machine.
---
template: tinted-slide
layout: true
---
name: concurrency
### Concurrency Versus Parallelism
The first step is to clarify the difference between .greenbold[concurrency]
and .greenbold[parallelism].
--
In [Chapter 3, Concurrency](chapter03.html#100), we stated that
two processes are .bluebold[concurrent] if their computations can .redbold[overlap in time].
The same is true of threads.
In contrast, two processes or threads execute .bluebold[in parallel] if they
execute .redbold[at the same time on different processors].
--
A .bluebold[parallel program] is one which contains instruction sequences that can be
executed in parallel.
--
If it is executed on a single processor, the threads within it can be interleaved in time
on the processor.
--
A parallel program therefore contains concurrency and can be called a .bluebold[concurrent program].
--
.redbold[The opposite is not true]: a system can have concurrency even though it is not
designed as a parallel program and its threads are not running on separate processors.
--
The next slide visualizes the distinction.
---
name: concurrency-visualized
### Visualizing Concurrency and Parallelism
Imagine four threads, T1, T2, T3, and T4, that can be executed in parallel.
If they are executed on a single core, as the top figure illustrates, the system
is called a concurrent system and the threads are executed .bluebold[concurrently].
If they are executed on two cores, as shown in the bottom figure,
with T1 and T4 on one core and T2 and T3 on the other, it is .bluebold[parallel execution].
.center[
<img src="figures/conc-parallel.png" width=65% alt="concurrent vs parallel">
]
---
name: parallel-challenges
### Challenges in Parallel Programming
It sounds simple enough - create programs that use all of the cores in the computer,
so that they run faster and utilize the cores fully.
--
Not so. Although the hardware manufacturers have been making processors
cheaper each year, packing more of them into computers, writing software for
multiprocessors is a .redbold[more difficult task] than writing
sequential code. The major problems are:
--
- .redbold[Functional Decomposition].
There is no algorithm to decompose a single task into multiple, independent,
parallel subtasks.
--
- .redbold[Load Balancing].
Decomposing a problem into subtasks in such a way
that each has roughly the same amount of computation, to maximize each core's utilization.
--
- .redbold[Data Decomposition].
Dividing the data among the subtasks to minimize IPC and divide the work equally,
and to do so in a scalable way.
--
- .redbold[Data Dependency Analysis].
When data is distributed to the various subtasks, identifying which data in each
subtask depends on the computation performed by a different subtask.
--
- .redbold[Testing and Debugging]. Unlike sequential software, parallel programs
can have errors that depend on the relative rates of execution of the subtasks.
Designing tests is very difficult and debugging when failure occur is even harder.
---
name: parallelism-models
### Sources of Parallelism in Problems
Two sources of inherent parallelism in computational problems are
.greenbold[data parallelism] and .greenbold[task parallelism] (also known as
.greenbold[functional parallelism].)
--
.bluebold[Data parallelism] exists when a task can be decomposed into many subtasks
that perform identical operations on different sets of data. Examples include
- A digital image on which the same operation must be applied to all pixels or
equal-size sub-regions of the image.
- The calculation of payroll taxes for all employees of a large company.
- A digital representation of a 3D shape that must be rotated through same angle in space, since
every point in the object undergoes the same linear transformation.
--
.bluebold[Task parallelism] exists when a task can be decomposed into multiple
subtasks such that each performs a different function, on the same or different
data sets. Examples include
- Analysis of census data by data sub-type, such as demographic analysis,
economic analysis, and geographic analysis.
- Audio data processing, in which audio data filters are applied one after another, in a pipeline.
---
name: parallelism-visualized
### Visual Comparison
.left-column[
A common source of data parallelism exists in linear arrays of data that need to be
sorted. Certain sorting algorithms are more amenable than others to decomposition into subtasks
that act on segments of the array. The diagram below depicts a variation of a parallel mergesort
algorithm.
<img src="figures/data_parallelism.png" width=110% alt="Data parallelism">
]
.right-column[
<img src="figures/task_parallelism.gif" width=100% alt="Task parallelism">
Meteorological data can be analyzed using a task decomposition. In the diagram above, the same
data is input to four different modeling algorithms, to build four different types of
environmental models.
]
---
name: speedup
### Speed-Up
Suppose that you want to add 1 to every element of an array of 1024 elements.
A sequential program would increment every element one after the other, performing
.redbold[1024 increment operations] sequentially.
--
If we had a machine with 1024 cores (not unreasonable in the scientific computing community),
and the know-how, we could write a program with 1024 threads that performed this same
computation .redbold[in the time it takes to execute a single increment].
--
.redbold[Right?]
--
Not exactly, because the threads have to access memory to do this, and they might be delayed because of
memory stalls. But let's pretend for now that this is not an issue.
--
The parallel program obviously takes about 1/1024.super[th] the time that the sequential program takes,
or it runs 1024 times faster. This leads to a definition.
--
.lightgreenbox[
The .bluebold[speed-up] of a parallel program with respect to a sequential program
on a computer with N identical processors with the exact same input data is the sequential
program's running time on one processor
divided by the parallel program's running time on N processors.
]
---
name: speed-up-limits
### Limitations of Parallelization
In 1967, .greenbold[Gene Amdahl] argued informally.super[1] that there was an
inherent limitation to the amount of speedup that could be obtained by using
more processors to perform a computation.
.footnote[
1 See the references at the end of the slides.
]
Although his original article contained no formulas whatsoever,
his argument was subsequently formulated mathematically and became known as
“.bluebold[Amdahl’s Law]”.
The starting premise is the following observation.
Every program has some fraction of operations in it that must be executed sequentially.
For example,
- reading from a file, and
- filling an array .fixedblue[A] such that .fixedblue[A[i+1]]'s value depends on .fixedblue[A[i]]'s
value for all .fixedblue[i]
are both inherently sequential. In other words, we cannot simultaneously update .fixedblue[A[i]]
and .fixedblue[A[i+1]].
---
name: amdahls-law
### Amdahl's Law
Let $f$ be the fraction of operations in a sequential program's computation on a given input that
are inherently sequential. $f$ is often called the .bluebold[serial fraction].
Let $N$ be the number of processing cores on the computer on which a parallel version
of this same program is run.
The speed-up of this parallel version using all $N$ processors has an upper bound given by the formula
$$
\text{speedup} \leq \frac{1}{f+\frac{(1-f)}{N}}
$$
The value $(1-f)$ is defined as the .bluebold[parallel fraction]. This represents the fraction
of code that can be run in parallel.
---
name: amdahl-examples
### Applications of Amdahl's Law
1. Suppose the serial fraction $f=0.2$. Then the upper bound on speedup for a machine with 8 cores is given by
$$
\text{speedup} \leq \frac{1}{0.2+\frac{(1-0.2)}{8}}=\frac{1}{0.2+\frac{(0.8)}{8}}=\frac{1}{0.2+0.1}=3.33
$$
--
1. Suppose the serial fraction is $f=0.04$. Then the upper bound on speedup for a machine with 8 cores is given by
$$
\text{speedup} \leq \frac{1}{0.04+\frac{(1-0.04)}{8}}=\frac{1}{0.04+\frac{(0.96)}{8}}=\frac{1}{0.04+0.12}=6.25
$$
--
If we increase the number of cores in this example from 8 to 32, how much better can we do?
$$
\text{speedup} \leq \frac{1}{0.04+\frac{(1-0.04)}{32}}=\frac{1}{0.04+\frac{(0.96)}{32}}=\frac{1}{0.04+0.03}=14.29
$$
--
.redbold[If we keep increasing the number of processors in this example, will speedup keep increasing?]
--
No.
---
name: amdahl-limit
### Maximum Possible Speedup
The serial fraction itself limits the maximum possible speedup. This is easy to prove.
Let $f$ be the serial fraction of operations in a given program.
Then the maximum possible speedup, given any number of processors, is the limit
$$
\lim_{N\rightarrow \infty} \left( \frac{1}{f+\frac{(1-f)}{N}} \right) =\frac{1}{f}
$$
--
- If $f=0.2$, the maximum speedup is $1/0.2=5$.
- If $f=0.5$, the maximum speedup is $1/0.5=2$.
- If $f=0.8$, the maximum speedup is $1/0.8=1.25$.
--
As $f\rightarrow 1$, the maximum possible speedup approaches $1$, meaning no speedup at all.
--
In short, .redbold[you cannot speed up a program that has little opportunity to be parallelized!]
---
name: amdahl-plot
### Plot of Amdahl's Law
Below is a plot of the speedup predicted by Amdahl's Law for various fractions of
inherently sequential code. The legend labels the curves using the parallel fraction $1-f$ rather than $f$.
.center[
<img src="figures/amdahls_law.png" width=70% alt="Amdahl's Law Plot">
]
.footnote[
Plot by Daniels220 at English Wikipedia, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=6678551
]
---
name: amdahl-activity
count: false
class: breakout
### Inverting Amdahl's Law
Suppose that $f$ is the serial fraction of operations in a given program.
The maximum possible speedup is $\frac{1}{f}$.
Suppose we want to achieve a specific speedup $S$ less than $\frac{1}{f}$.
How many processors are needed?
1. Use the formula for speedup to write $N$ as a function of $f$ and $S$.
2. For $f=0.1$, find the least number of processors needed to obtain a speedup of
$5$.
3. What if we want a speedup of $8$?
---
name: multithreading
layout: false
class: center, middle, inverse
## Multi-threading Models for Explicit Threading
We examine different methods of implementing support for programmer-defined threads.
---
template: tinted-slide
layout: true
---
name: multithreading-models
### Multi-threading Models
Ultimately the goal is to be able to write programs that create threads and manipulate them.
How can one do this?
--
- Are threads built into programming languages?
--
- Are they supported through the use of special libraries to which a program can link?
--
- Are they supported directly by the kernel, so that a program must request thread
services directly from the kernel?
--
These are all valid questions, and by the end of this section you will understand
what the various options are and what limitations each has.
--
We are about to explore two different methods by which computer systems
allow programmers to create multithreaded programs. They are called .bluebold[multithreading models].
.redbold[The difference between the methods is that, in one,
threads are implemented in user space, and in the other,
in kernel space.]
---
name: thread-types
### Thread Implementations
There are two general ways in which threads can be implemented, which are often called
.greenbold[user level threads] and .greenbold[kernel level threads].
--
.bluebold[User level threads] are threads that are managed by a user level thread library.
The thread library contains code for creating and destroying threads,
for inter-thread communication, scheduling, saving and restoring thread contexts, and all
other thread management operations.
The three most commonly used thread libraries are .fixedblue[POSIX Threads],
.fixedblue[Windows Threads], and .fixedblue[Java Threads].
--
.bluebold[Kernel level threads] are managed entirely within the kernel.
There is no thread management code in user space.
Creating, destroying, scheduling, coordinating, and otherwise managing threads
is performed completely within kernel code.
A kernel level thread is sometimes
called a .bluebold[light weight process] (.bluebold[LWP]).
Almost all modern operating systems support kernel level threads.
--
We begin by examining user level threads.
After that we examine kernel level threads.
---
name: user-threads-1
### User Level Threads
User level threads are implemented by special thread libraries. A program with multiple threads
is linked into the thread library, which handles all aspects of thread management.
In the figure below, there are two processes, one with 4 user threads, the other, with 3.
.center[
<img src="figures/user-threads.png" width=65% alt="user threads">
]
The thread support is handled within the library entirely, in user space.
Notice that there are no threads depicted in the kernel in this figure.
With user level threads, it is possible to have a multithreaded program in an operating system that
may or may not have kernel support for threading. It is independent of kernel support.
---
name: pthreads-example-1
### A POSIX Threads Example
One of the most common user thread libraries is the one standardized by .greenbold[POSIX],
which specifies an API for multithreaded programs
commonly known as .bluebold[POSIX threads] or .bluebold[Pthreads].
This interface is implemented in almost all modern operating systems.
Below is a simple example of a Pthreads program that creates a single
child thread.
```C
#include <pthread.h> /* Includes of other header files omitted to save space */
void * hello_world( void * unused)
{
printf("The child says, \"Hello world!\"\n");
`pthread_exit(NULL)` ;
}
int main( int argc, char *argv[])
{
pthread_t child_thread;
/* Create and launch thread */
if ( 0 != `pthread_create(&child_thread, NULL, hello_world, NULL )` ){
exit(1);
}
printf("This is the parent thread.\n");
`pthread_join(child_thread, NULL)`; /* Wait for the child thread to terminate. */
return 0;
}
```
---
name: pthreads-2
### Some Explanation
In the preceding program, we highlighted the three calls to functions from
the Pthreads API:
```C
pthread_exit()
pthread_create()
pthread_join()
```
The .fixedblue[pthread_exit()] call terminates the calling thread.
The .fixedblue[pthread_create()] call creates a new thread, called the .greenbold[child] thread.
The caller is the .greenbold[parent] thread.
The .fixedblue[pthread_join()] call makes the main program wait until the
child thread makes a call to .fixedblue[pthread_exit()].
--
An important point about these functions is that the library implements them
by making calls to the underlying operating system thread support system, if it exists.
If not, it simulates the operations within the process. This will be explained more later.
---
name: fork-join-2
### Fork-Join Flow
The parallel flow when .fixedblue[pthread_create()] and .fixedblue[pthread_join()]
are used is illustrated by the diagram below.
.center[
<img src="figures/fork-join-simple.png" width=80% alt="fork-join diagram">
]
--
Notice that, after the .fixedblue[join()] call, only the parent thread continues.
In this paradigm, a thread creates a child thread and waits for it to finish,
after which only the parent thread continues.
When multiple threads need to be created, the flow looks something like the diagram below.
There is no way to create more than one thread at a time.
.center[
<img src="figures/pthread-fork-join.png" width=100% alt="fork-join parallelism">
]
--
The fork-join paradigm is fundamental to how multithreading is achieved in thread libraries
such as Pthreads.
It also underlies a type of threading model known as .redbold[fork-join parallelism]
which we will discuss later in this chapter.
---
name: pthread-activity
count: false