Table of Contents
Table of Contents
with
POSIX® Threads
David R. Butenhof
:vAddison-Wesley
Boston • San Francisco • New York • Toronto • Montreal
London • Munich • Paris • Madrid
Capetown • Sidney • Tokyo • Singapore • Mexico City
Contents
1 Introduction 1
1.1 The "bailing programmers" 3
1.2 Definitions and terminology 4
1.2.1 Asynchronous 4
1.2.2 Concurrency 4
1.2.3 Uniprocessor and multiprocessor 5
1.2.4 Parallelism 5
1.2.5 Thread safety and reentrancy 6
1.2.6 Concurrency control functions 7
1.3 Asynchronous programming is intuitive 8
1.3.1 . . . because UNIX is asynchronous 9
1.3.2 . . . because the world is asynchronous 11
1.4 About the examples in this book 12
1.5 Asynchronous programming, by example 13
1.5.1 The baseline, synchronous version 14
1.5.2 A version using multiple processes 15
1.5.3 Aversion using multiple threads 17
1.5.4 Summary 19
1.6 Benefits of threading 20
1.6.1 Parallelism 20
1.6.2 Concurrency 22
1.6.3 Programming model 24
1.7 Costs of threading 25
1.7.1 Computing overhead 26
1.7.2 Programming discipline 26
1.7.3 Harder to debug 27
1.8 To thread or not to thread? 28
1.9 POSIX thread concepts 29
1.9.1 Architectural overview 30
1.9.2 Types and interfaces 30
vi i
Contents
viii
35
2 Threads
2.1 Creating and using threads 35
2.2 The Life of a thread 39
2.2.1 Creation 40
2.2.2 Startup 41
2.2.3 Running and blocking 42
2.2.4 Termination 43
2.2.5 Recycling 44
3 Synchronization 45
3.1 Invariants, critical sections, and predicates 45
3.2 Mutexes 47
3.2.1 Creating and destroying a mutex 49
3.2.2 Locking and =locking a mutex 52
3.2.2.1 Nonblocking mutex locks 58
3.2.3 Using mutexes for atomicity 61
3.2.4 Sizing a mutex to fit the job 62
3.2.5 Using more than one mutex 63
3.2.5.1 Lock hierarchy 63
3.2.5.2 Lock chaining 70
3.3 Condition variables 70
3.3.1 Creating and destroying a condition variable 74
3.3.2 Waiting an a condition variable 77
3.3.3 Waking condition variable waiters 81
3.3.4 One final alarm program 82
3.4 Memory visibility between threads 88
Bibliography 363
Thread resources an the Internet 367
Index 369