Download presentation
Presentation is loading. Please wait.
Published byLinda Thompson Modified over 5 years ago
1
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio
2
What is a Thread?
3
How are Threads Different Than Processes?
4
Why Use Threads?
5
What Can Go Wrong With Threads?
Safety hazards “Program does the wrong thing” Liveness hazards “Program never does the right thing” e.g., deadlock Performance hazards Program is too slow due to excessive synchronization
6
Review: Thread Scheduling
Scheduler decides when to run runnable threads Programs should make no assumptions about the scheduler Scheduler is a “black box” 1 2 3 4 5 scheduler {4, 2, 3, 5, 1, 3, 4, 5, 2, …} CPU
7
Thread Safety Definition: A program is thread safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of those threads Race condition: program’s output is different depending on scheduler interleavings Almost always a bug
8
public class ThreadTest extends Thread {
private static int x = 7; public void run () { x++; } public static void main (String [] args) { Thread t1 = new ThreadTest(); Thread t2 = new ThreadTest(); t1.start(); t2.start(); try { t1.join(); // wait for thread to finish t2.join(); // wait for thread to finish catch (InterruptedException iex) { } System.out.println("Value of x: " + x);
9
Safety Hazard: Incrementing X
Key point: x++ is multiple operations Load x from memory; increment; store Or, in MIPS assembly: lw $t, offset($s) addi $t, $t, 1 sw $t, offset($s)
10
Unsafe Thread Schedule
Given Thread 1 and Thread 2: Final result: x == 8 lw $t, offset($s) addi $t, $t, 1 sw $t, offset($s) time
11
Solution #1: Synchronized Block
public class ThreadTest extends Thread { private static int x = 7; private static Object lockObject = new Object(); public void run () { synchronized(lockObject) { // only one thread can execute in here! x++; } // … What would happen if the lock object were not static?
12
Vocabulary Atomic: Section of code that executes without interleaving instructions from other threads “all-or-nothing” execution Critical Section: Section of code that accesses a shared resource Must be accessed atomically
13
Solution #2: Atomic Variable
public class ThreadTest extends Thread { private static final x = new AtomicInteger(); public void run () { x.incrementAndGet(); } // … Note: not synchronized!
14
Rule #1 All shared, mutable state must be properly synchronized
Usually with a synchronized block or method Key challenge: figuring out which state is shared and mutable … More on this to come
15
Another Example: AspectRatio
16
[Discussion of AspectRatio.java]
17
Rule #2 Compound actions must be protected by a single lock
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.