Douglas C. Schmidt - Concurrent object-oriented network programming in C++
Object-Oriented Software Engineering Concurrent Programming.
-
date post
19-Dec-2015 -
Category
Documents
-
view
213 -
download
0
Transcript of Object-Oriented Software Engineering Concurrent Programming.
Object-Oriented Software Engineering
Concurrent Programming
Contents
•Threads and Processes
•Race Conditions
•Deadlocks
•Extending Thread Class
•Overriding run ( )
• sleep ( )
•Using threads
• Interleaving
Threads vs. Processes
• A process is an independent flow of control
• There is no shared memory space among different processes
• Processes communicate between each other by specific communication channels (not shared variables)
• e.g. Pipes in Unix, e.g.
ls | more
Threads vs. Processes
• A thread is a single flow of control within a program
• It performs one of the tasks that a program needs to perform to achieve its goals
• If a program needs to perform several tasks, these could be handled in different threads (and hence performed concurrently)
• These threads will interact and cooperate through a shared memory space
Threads vs. Processes
• Different threads can interact via shared variables and objects
• The execution of each thread may proceed independently of the others
• In general, the relative ordering of execution of the different threads is non-deterministic
• This can lead to safety and liveness problems
Race Conditions
A:Thread Data: B:Thread
a) We expect this to happen
set
A:Thread Data: B:Thread
b) Delay in A can cause wrong behavior
set
get get
Deadlocks
Suppose we extend the File class to MyFile.MyFile has copy method.
fle1.copy(fle2)
copies contents of fle1 to fle2.
File
MyFileFile copy(File file)
Deadlocks
fle1.copy(fle2)
1. obtains write lock for fle1
2. reads in contents of fle1
3. obtains write lock for fle2
4. writes contents to fle2
5. release all locks
File
MyFileFile copy(File file)
Consider what could happen for separatethreads that execute:
Thread 1: fle1.copy(fle2)Thread 2: fle2.copy(fle1)
Deadlocks
fle2: MyFilefle1.copy(fle2) fle1: MyFile
get lock
read contents
get lock
write contents
release lock
release lock
object executing this code
Deadlocks
Thread 2fle2: MyFileThread 1 fle1: MyFile
get lock get lock
read contentsread contents
get lock
get lock
Method calls will NOT return.Both threads are waiting for the other to release a lock before they can get the lock!
Two ways to have threads
MyThread
void run( )void interrupt( )
void join( )String getName( )boolean isAlive( )
........
MyThread
run( )
Object
Thread <<interface>>Runnable
For all Thread methods see:http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#method_summary
Extending Threadpublic class SimpleThread extends Thread { public static String destination = ""; public boolean notFinished = true;
public SimpleThread(String str) { super(str); }
public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) { } }
System.out.println("DONE! " + getName()); destination = getName(); //set CLASS field now finished notFinished = false; //so this thread has finished }}
Complete code for this lecture available on web site for course
Overriding run( ) methodpublic void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) { } }
System.out.println("DONE! " + getName());destination = getName(); //set CLASS field now finishednotFinished = false; //so this thread has finished
}
For a thread to do anything interesting while being executed must override the run( ) method.
sleep method causesthread to suspend while timer is running
must catch exception ifsleep is interrupted
sleep method
public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) { } }
System.out.println("DONE! " + getName());destination = getName(); //set CLASS field now finishednotFinished = false; //so this thread has finished
}
Thread can not be executed for this amount of time
Once sleep is overthis thread will taketurns at being executedas before
sleep method
• sleep ( ) can be used to give threadsbetter chance of having fair share ofexecution
• sleep ( ) can be used to delay threadwhile it waits for resources to becomeavailable
Using Threadspublic class TwoThreadsDemo {
public static void main (String[ ] args) {SimpleThread Jam = new SimpleThread("Jamaica");SimpleThread Fij = new SimpleThread("Fiji");
Jam.start(); Fij.start();
while ((Jam.notFinished) | (Fij.notFinished)) { // do nothing big waste of time}
JOptionPane.showMessageDialog(null, Fij.destination, "The winner is ", JOptionPane.PLAIN_MESSAGE);
}}
Note start methodsare pre-defined
Interleaving threadsAs the Java run time environment executes the TwoThreadsDemo java application it starts each thread in turn.
Jam.start();Fij.start();
This causes Java to execute the run methods for Jam and Fij.Java sequentially executes the code in the run methods.
At each point in the execution Java randomly chooses which thread to pick next.
After Java executes a single expression from one thread, it then randomly chooses either:1. to execute the next expression for Jam2. or execute the next expression for Fij
At the same time the execution of TwoThreadsDemo continuesindependently from the threads.
Threads, random interleaving
expression:2
TwoThreadsDemo Jam thread Fij thread
expression:5
expression:8
Java
expression:4
expression:6
expression:7
expression:1
expression:3
expression:9
Interleaving Fairness
• Java chooses randomly between threads
• Does not have to be fair
• That is one thread may be executed more often thananother
• Java will always execute the expressions in a threadeventually
Warning about expressions
for (int i = 0; i < 10; i++) { // and so on}
expression:1 expression:2
expression:3
• Each of these expressions may be interleaved betweenthose from other threads during execution.
• Don't assume that a single line of code is a single expressionthat will be executed all in one go!
Expression interleaving
Fij: i < 10
Jam: int i = 0
Fij: i++
Jam: i < 10
Fij: // and so on
Fij: i < 10
Traces from interleaving threads
Thread_1
public void run( ) {a;b;c;
}
Thread_2
public void run( ) {x;y;z;
}
All possible traces from Thread 1 and Thread 2
4
5
6
7
a
b
c
0
1
2
3
a
b
c8
9
10
11
a
b
c
12
13
14
15
a
b
c
x
x
x
x
y
y
y
y
z
z
z
z
Thread_1.start();Thread_2.start();
Paths from topto bottom give alltraces from interleaving.20 in total