Threads
Threads
Concurrent Programming
with Threads:
Why you should care deeply
Don Porter
Portions courtesy Emmett Witchel
1
COMP 530: Operating Systems
10000
20% /year
1000
52% /year
100
10
25% /year
1
1978 1980 1982 1984 1986 1988 1990 1992 1994 1996 1998 2000 2002 2004 2006
Transistor Budget
• We have an increasing glut of transistors
– (at least for a few more years)
• But we can’t use them to make things faster
– Techniques that worked in the 90s blew up heat faster
than we can dissipate it
• What to do?
– Use the increasing transistor budget to make more cores!
5
COMP 530: Operating Systems
6
COMP 530: Operating Systems
8
COMP 530: Operating Systems
Practical Difference
• With processes, you coordinate through nice
abstractions (relatively speaking – e.g., lab 1)
– Pipes, signals, etc.
• With threads, you communicate through data
structures in your process virtual address space
– Just read/write variables and pointers
9
COMP 530: Operating Systems
Programmer’s View
main() {
…
tid = CreateThread(fn1, arg0, arg1, …);
…
}
0 0xffffffff
• 2 threads requires 2 stacks in the process
• No problem!
• Kernel can schedule each thread separately
– Possibly on 2 CPUs
– Requires some extra bookkeeping
COMP 530: Operating Systems
Start Done
Ready Running
Waiting
COMP 530: Operating Systems
Lecture Outline
• What are threads?
• Small digression: Performance Analysis
– There will be a few more of these in upcoming lectures
• Why are threads hard?
21
COMP 530: Operating Systems
Questions
• Do the following either completely succeed or
completely fail?
• Writing an 8-bit byte to memory
– A. Yes B. No
• Creating a file
– A. Yes B. No
• Writing a 512-byte disk sector
– A. Yes B. No
COMP 530: Operating Systems
Thread1: x = 1; Thread2: x = 2;
Initially y = 10;
Thread1: x = y + 1; Thread2: y = y * 2;
Initially x = 0;
Thread1: x = x + 1; Thread2: x = x + 2;
COMP 530: Operating Systems
Critical Sections
• Key abstraction: A group of instructions that cannot
be interleaved
• Generally, critical sections execute under mutual
exclusion
– E.g., a critical section is the part of the recipe involving
butter and salt – you know, the important part
• One critical section may wait for another
– Key to good multi-core performance is minimizing the time
in critical sections
• While still rendering correct code!
31
COMP 530: Operating Systems
lprev lptr
COMP 530: Operating Systems
lprev lptr
COMP 530: Operating Systems
Lecture Summary
• Understand the distinction between process &
thread
• Understand motivation for threads
• Concepts of Throughput vs. Latency
• Intuition of why coordinating threads is hard
• Idea of mutual exclusion and critical sections
– Much more on last two points to come
40