Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia or
Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia or
Distributed Applications:
Multithreaded
Programming using Java
Threads
Rajkumar Buyya
Grid Computing and Distributed Systems (GRIDS)
Laboratory
Dept. of Computer Science and Software Engineering
University of Melbourne, Australia
http://www.gridbus.org/~raj or http://www.buyya.com
1
Outline
Introduction
Thread Applications
Defining Threads
Java Threads and States
Architecture of Multithreaded servers
Threads Synchronization
Thread Concurrency Models
Summary
2
Introduction
OS: kernel,
libraries &
servers
OS1
Processes, threads,
communication, ...
OS2
Processes, threads,
communication, ...
Computer &
network hardware
Computer &
network hardware
Node 1
Platform
Node 2
Unix and Windows are two examples of Network Operating Systems have a
networking capability built into them and so can be used to access remote
resources using basic services such as rlogin, telnet.
Communication
manager
Thread manager
Memory manager
Supervisor
..
}
begin
body
end
}
7
A Multithreaded Program
Main Thread
start
Thread A
start
Thread B
start
Thread C
Multiplethreaded
Threads of Process
Execution
Application
Application
CPU
CPU
CPU
Better Response Times in
Multiple Application
Environments
CPU
CPU
CPU
Web/Internet Applications:
Serving Many Users
Simultaneously
PC client
Internet
Server
Local Area Network
PDA
11
Server Process
Client 1
Process
Server
Threads
Internet
Client 2
Process
12
Editing
Editing
Thread
Thread
13
Multithreaded/Parallel File
Copy
reader()
reader()
{{
-- -- -- -- -- -- -- -- --lock(buff[i]);
lock(buff[i]);
read(src,buff[i]);
read(src,buff[i]);
unlock(buff[i]);
unlock(buff[i]);
-- -- -- -- -- -- -- -- --}}
buff[0]
buff[0]
buff[1]
buff[1]
writer()
writer()
{{
-- -- -- -- -- -- -- -- -- -lock(buff[i]);
lock(buff[i]);
write(src,buff[i]);
write(src,buff[i]);
unlock(buff[i]);
unlock(buff[i]);
-- -- -- -- -- -- -- -- -- -}}
Cooperative
Cooperative Parallel
Parallel
Synchronized
Synchronized Threads
Threads
14
Levels of Parallelism
Sockets/
PVM/MPI
Threads
Compilers
CPU
Task
Taski-l
i-l
func1
func1( () )
{{
....
....
....
....
}}
++
Task
Taskii
func2
func2( () )
{{
....
....
....
....
}}
aa( (11)=..
)=..
bb( (11)=..
)=..
xx
Task
Taski+1
i+1
func3
func3( () )
{{
....
....
....
....
}}
aa( (22)=..
)=..
bb( (22)=..
)=..
Load
Load
Code-Granularity
Code-Granularity
Code
CodeItem
Item
Large
Largegrain
grain
(task
(tasklevel)
level)
Program
Program
Medium
Mediumgrain
grain
(control
(controllevel)
level)
Function
Function(thread)
(thread)
Fine
Finegrain
grain
(data
(datalevel)
level)
Loop
Loop(Compiler)
(Compiler)
Very
Veryfine
finegrain
grain
(multiple
(multipleissue)
issue)
With
Withhardware
hardware
15
Multithreading Multiprocessors
Process
Process Parallelism
Parallelism
CPU
P1
P1
P2
P2
CPU
P3
P3
CPU
tim
tim
ee
No
No of
of execution
execution process
process more
more the
the
number
number of
of CPUs
CPUs
16
Multithreading on Uniprocessor
Concurrency Vs Parallelism
Process
ProcessConcurrency
Concurrency
P1
P1
P2
P2
CPU
P3
P3
tim
tim
ee
Number
Number of
of Simultaneous
Simultaneous execution
execution units
units >
>
number
number of
of CPUs
CPUs
17
Java Threads
currentThread
start setPriority
yield run getPriority
sleep stop suspend
resume
Threading Mechanisms...
20
Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:
thr1.start();
Create and Execute:
new MyThread().start();
21
An example
class MyThread extends Thread { // the thread
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx1 {
// a program that utilizes the thread
public static void main(String [] args ) {
MyThread t = new MyThread();
MyThread t2 = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
t2.start();
t.start();
} // end main()
}
// end class ThreadEx1
22
Next Lecture
Using interfaces
Multiple threads in a program
23
24
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
}
// end class ThreadEx2
25
wait()
sleep()
suspend()
blocked
runnable
stop()
dead
non-runnable
notify()
slept
resume()
unblocked
26
27
28
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
29
Run 1
[raj@mundroo] threads [1:76] java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
30
Run2
[raj@mundroo] threads [1:77] java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
31
Partitioning: Process
Parallelism
IS1
pthread
pthreadt1,
t1,t2;
t2;
pthread-create(&t1,
pthread-create(&t1,add,
add,a,b,
a,b,&&r1);
r1);
pthread-create(&t2,
pthread-create(&t2,sub,
sub,c,d,
c,d,&&r2);
r2);
pthread-par
pthread-par(2,
(2,t1,
t1,t2);
t2);
add
add
Processor
IS2
sub
sub
Data
aa
bb
r1
r1
cc
dd
r2
r2
pthread-t,
pthread-t,thread1,
thread1,thread2;
thread2;
pthread-create(&
pthread-create(&thread1,
thread1,sort,
sort,array,
array,N/2);
N/2);
pthread-create(&
pthread-create(&thread2,
thread2,sort,
sort,array,
array,N/2);
N/2);
pthread-par(2,
thread1,
thread2);
pthread-par(2, thread1, thread2);
Data
Processor
Sort
Sort
IS
Processor
Sort
Sort
SIMD Processing
do
dn/2
dn2/+1
dn
33
Multithreaded Server
Multithreaded Server
Client
Process
Server Process
Server
Threads
Client Process
User Mode
Kernel Mode
Message Passing
Facility
34
Architectures:
Worker pool
Thread-per-request
Thread-per-connection
Thread-per-object
35
Input-output
Receipt &
queuing
T1
Requests
N threads
Client
Server
36
a. Thread-per-request
remote
objects
per-connection threads
remote
objects
b. Thread-per-connection
per-object threads
I/O
remote
objects
c. Thread-per-object
37
A Client Program
What is the Meaning of (Love)?
Love
Multithreaded
Dictionary Server
A deep, tender, inefable feeling of (try, dictionary.com)
afection and solicitude toward a
person
Solicitude
care or concern, as for
the well-being of
A Client Program
another
What is the Meaning of (Love)?
A Client
Program in C
A Client
Program in C++
38
Next Lecture
Thread Synchronisation
Thread Priorities
39
Deposit()
Withdraw()
Enquire()
40
Internet Bank
Server
Local Area Network
Bank
Database
PDA
41
Shared Resources
}
42
t1.start();
t2.start();
t3.start();
// DO some other operation
} // end main()
}
43
accoun
t
(shared
object)
44
}
45
Thread Priority
ThreadName.setPriority(intNumber)
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY=10
46
47
48
Thread Programming
Thread concurrency/operation
models
models
49
Resources
Workers
taskX
taskX
Files
Databases
Master
Input (Stream)
main
main( () )
taskY
taskY
Disks
taskZ
taskZ
Special
Devices
50
Example
51
Input
Input
Resources
Workers
taskX
taskX
Files
Databases
taskY
taskY
Disks
taskZ
taskZ
Special
Devices
52
Example
main()
{
pthread_create(....,thread1...taskX);
pthread_create(....,thread2...taskY);
....
signal all workers to start
wait for all workers to finish
do any cleanup
}
}
taskX() /* worker */
{
wait for start
perform the task, sync if accessing shared resources
}
taskY() /* worker */
{
wait for start
perform the task, sync if accessing shared resources
}
53
thread pipeline
A thread Apipeline
Program
Filter Threads
Stage
Stage11
Stage
Stage22
Stage
Stage33
Input (Stream)
Resources
Files
Files
Files
Databases
Databases
Databases
Disks
Special Devices
Disks
Special Devices
Disks
Special Devices
54
Example
main()
{
pthread_create(....,stage1);
pthread_create(....,stage2);
....
wait for all pipeline threads to finish
do any cleanup
}
stage1() {
get next input for the program
do stage 1 processing of the input
pass result to next thread in pipeline
}
stage2(){
get input from previous thread in pipeline
do stage 2 processing of the input
pass result to next thread in pipeline
}
stageN()
{
get input from previous thread in pipeline
do stage N processing of the input
pass result to program output.
}
55
57
Scheduler activations
Process
A
P added
SA preempted
Process
B
Process
SA unblocked
SA blocked
Kernel
Virtual processors
A. Assignment of virtual processors
to processes
Kernel
P idle
P needed
58
Thread
Kernel
Protection domain
boundary
Thread 1
User 1
Thread 2
Kernel
User 2
Network
Thread 1
Thread 2
User 1
User 2
Kernel 1
Kernel 2
59
Requested data
size (bytes)
0
1000
2000
Packet
size
60
A lightweight remote
procedure call
Client
Server
A stack
A
4. Execute procedure
and copy results
1. Copy args
User
stub
stub
Kernel
2. Trap to Kernel
3. Upcall
5. Return (trap)
61
process args
marshal
Send
Receive
unmarshal
process results
process args
marshal
Send
Concurrent invocations
process args
marshal
Send
transmission
process args
marshal
Send
Receive
unmarshal
execute request
marshal
Send
Receive
unmarshal
process results
Receive
unmarshal
execute request
marshal
Send
Receive
unmarshal
execute request
marshal
Send
Receive
unmarshal
process results
Receive
unmarshal
execute request
marshal
Send
time
Receive
unmarshal
process results
Client
Server
Client
Server
62
Summary
Worker pool
Thread-per-request
Thread-per-connection
Thread-per-object