Download Threads and Synchronization in CMSC 433: A Java Perspective - Prof. Adam A. Porter and more Study notes Programming Languages in PDF only on Docsity!
CMSC 433, Adam Porter, U. Maryland (via
CMSC433, Fall 2002
Programming Language Technology and Paradigms
Threads and Synchronization
Adam Porter
CMCS 433, Fall 2002 - Adam Porter 2
Overview
• What are threads?
• Thread scheduling, data races, and
synchronization
• Thread mechanisms in Java
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 3
Computation Abstractions
CPU 1 CPU 2
p1 p2 p3 p
t
t
t
t
t
t
t
t
A computer
Processes
(e.g. JVM’s)
Threads
CMCS 433, Fall 2002 - Adam Porter 4
Processes vs. Threads
int x;
foo() {
…x…
int x;
foo() {
…x…
int x;
foo() { …x… }
foo() { …x… }
Processes do not
share data
Threads share data
within a process
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 7
Programming Threads
• Most languages have threads
– C, C++, Objective Caml, Java, SmallTalk …
• The thread API differs with each, but most
have the basic features we will now present
CMCS 433, Fall 2002 - Adam Porter 8
Thread Applications
• Web browsers
– one thread for I/O
– one thread for each file being downloaded
– one thread to render web page
• Graphical User Interfaces (GUIs)
– Have one thread waiting for each important
event, like key press, button press, etc.
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 9
Thread Scheduling
• OS schedules a single-threaded process on a
single processor
• Multithreaded process scheduling:
– One thread per processor
- Effectively splits a process across CPU’s
- Exploits hardware-level concurrency
– Many threads per processor
- Need to share CPU in slices of time
CMCS 433, Fall 2002 - Adam Porter 10
Scheduling Example (1)
CPU 1
CPU 2
p
p
p
p
One process per CPU
p2 threads: p1 threads:
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 13
Data Races
• Data shared between threads can become
corrupted due to “inopportune” scheduling
of the sharing threads. These are called
“data races.”
• Therefore need to selectively control the
scheduler to avoid such data accesses. This
is usually done via synchronization.
CMCS 433, Fall 2002 - Adam Porter 14
Data Race Example
int cnt = 0;
void thread1() {
int y = cnt;
cnt = y + 1;
void thread2() {
int y = cnt;
cnt = y + 1;
cnt = 0
Start: both threads ready to
run. Each will increment the
global count.
Shared state
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 15
Data Race Example
int cnt = 0;
void thread1() {
int y = cnt;
cnt = y + 1;
void thread2() {
int y = cnt;
cnt = y + 1;
cnt = 0
Thread1 executes, grabbing
the global counter value into y.
Shared state
y = 0
CMCS 433, Fall 2002 - Adam Porter 16
Data Race Example
int cnt = 0;
void thread1() {
int y = cnt;
cnt = y + 1;
void thread2() {
int y = cnt;
cnt = y + 1;
cnt = 0
Thread1 is pre-empted. Thread
executes, grabbing the global
counter value into y.
Shared state
y = 0
y = 0
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 19
What happened?
• Thread1 was preempted after it read the
counter but before it stored the new value.
• A particular way in which the execution of
two threads is interleaved is called a
schedule. We want to prevent this
undesirable schedule.
• Undesirable schedules can be hard to
reproduce, and so hard to debug.
CMCS 433, Fall 2002 - Adam Porter 20
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 0
Lock , for protecting the
shared state
Acquires the lock; only
succeeds if not held by
another thread
Releases the lock
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 21
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 0
Thread1 acquires lock l
CMCS 433, Fall 2002 - Adam Porter 22
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 0
Thread1 reads cnt into y
y = 0
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 25
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 1
Thread1 releases the lock
and terminates
y = 0
CMCS 433, Fall 2002 - Adam Porter 26
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 1
Thread2 now can acquire
lock l.
y = 0
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 27
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 1
Thread2 reads cnt into y.
y = 0
y = 1
CMCS 433, Fall 2002 - Adam Porter 28
Applying synchronization
int cnt = 0; lock l; void thread1() { synchronized(l) { int y = cnt; cnt = y + 1; } } void thread2() { synchronized(l) { int y = cnt; cnt = y + 1; } }
Shared state cnt = 2
Thread2 assigns cnt,
then releases the lock
y = 0
y = 1
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 31
Thread Lifecycle
• While a thread executes, it goes through a
number of different phases
– New : created but not yet started
– Runnable : either running, or able to run on a
free CPU
– Blocked : waiting for I/O or on a lock
– Sleeping : paused for a user-specified specified
interval
CMCS 433, Fall 2002 - Adam Porter 32
Java Threads
• The class java.lang.Thread
– Implements the basic threading abstraction
– Can extend this class to create your own threads
• The interface java.lang.Runnable
– Can create a thread by passing it a class that
implements this interface
– Favors composition over inheritance; more
flexible
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 33
Extending class Thread
• Can build a thread class by extending
java.lang.Thread
• Must supply a public void run() method
• Start a thread by invoking the start() method
• When a thread starts, executes run()
• When run() returns, thread is finished/dead
CMCS 433, Fall 2002 - Adam Porter 34
Example: Synchronous alarms
while (true) {
System.out.print("Alarm> ");
// read user input
String line = b.readLine();
parseInput(line);
// wait (in secs)
try {
Thread.sleep(timeout * 1000);
} catch (InterruptedException e) { }
System.out.println("("+timeout+") "+msg);
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 37
Runnable interface
• Extending Thread means can’t extend any other
class
• Instead implement Runnable
- declares that the class has a void run() method
• Can construct a new Thread
- and give it an object of type Runnable as an argument
to the constructor
- Thread(Runnable target)
- Thread(Runnable target, String name)
CMCS 433, Fall 2002 - Adam Porter 38
Thread example revisited
public class AlarmRunnable implements Runnable { private String msg = null; private int timeout = 0;
public AlarmRunnable(String msg, int time) { this.msg = msg; this.timeout = time; }
public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } }
CMSC 433, Adam Porter, U. Maryland (via
CMCS 433, Fall 2002 - Adam Porter 39
Change is in object creation
• Old parseInput does
– return new AlarmThread(m,t);
• New parseInput does
– return new Thread(new AlarmRunnable(m,t));
• Code in while loop doesn’t change
CMCS 433, Fall 2002 - Adam Porter 40
Another example
public class ThreadDemo implements Runnable { public void run() { for (int i = 5; i > 0; i--) { System.out.println(i); try { Thread.sleep(1000); } catch(InterruptedException e) { }; } System.out.println(“exiting “ + Thread.currentThread()); } public static void main(String [] args) { Thread t = new Thread(new ThreadDemo(), ”Demo Thread”); System.out.println(“main thread: “ + Thread.currentThread()); System.out.println(“Thread created: “ + t); t.start(); try { Thread.sleep(3000); } catch (InterruptedException e) {}; System.out.println(“exiting “+Thread.currentThread()); } }