IA010: Principles of Programming Languages: 9. Concurrency
IA010: Principles of Programming Languages: 9. Concurrency
Languages
9. Concurrency
IA010 9. Concurrency 1
Motivation
IA010 9. Concurrency 2
Concurrency
Levels of concurrency
• machine instructions
• statements (blocks of statements)
• subroutines (procedures, functions)
• whole programs
Goals
• scalability
(the speed increases with each added processor)
• portability
(reflects the speed of hardware development)
IA010 9. Concurrency 3
Outline
Semaphores
Monitors
Concurrency in Java
Message passing
IA010 9. Concurrency 4
Concurrency: basic principles
IA010 9. Concurrency 5
Multiprocessor architectures
IA010 9. Concurrency 6
Categories of concurrency
• physical concurrency
• several program units literally “execute simultaneously”
• logical concurrency
• the execution is interleaved on a single processor
• but to the outside the environment looks as concurrent
• quasi-concurrency
• coroutines – not true concurrency
IA010 9. Concurrency 7
Basic concepts
• task
• a program unit, which can be executed independently of
other units
• sometimes called a process or a thread
• differences between tasks and subroutines:
1 a task can be executed implicitly
2 unit, which executes a task, may not necessarily wait for it
to finish
3 after a task is finished, the execution can continue from a
different point than the point of task execution
• heavyweight tasks
• each task has its own address space
• lightweight tasks
• all lightweight tasks share the same address space
• easier for the programmers
• can be more efficient (less overhead)
IA010 9. Concurrency 8
Basic concepts 2
task communication
• through shared variables
• message passing
• using parameters
synchronization
• a mechanism for controlling the task execution order
• cooperation synchronization
• one task waits for the other
• typical problem: producer-consumer
• competition synchronization
• several tasks compete for an access to a limited resource
• typical problem: mutual exclusion
• scheduler
• run-time system, which governs processor sharing among
tasks
IA010 9. Concurrency 9
Producers-consumers
IA010 9. Concurrency 10
Mutual exclusion
task A; task B;
x = x + 1; x = x * 2;
end A; end B;
deadlock
• if two or more tasks wait for each other
• example (tasks: A, B; resources: X, Y):
1 task A requests and obtains the resource X
2 task B requests and obtains the resource Y
3 task A requests the resource Y (requires X and Y)
4 task B requests the resource X (requires X and Y)
5 A and B mutually wain one for the other
IA010 9. Concurrency 13
Language designs for oncurrency
IA010 9. Concurrency 14
OpenMP example
#pragma omp for
for(int n=0; n<10; ++n) {
printf(" %d", n);
}
printf(".\n");
generated code
int this_thread = omp_get_thread_num();
int num_threads = omp_get_num_threads();
int my_start = (this_thread ) * 10 / num_threads;
int my_end = (this_thread+1) * 10 / num_threads;
for(int n=my_start; n<my_end; ++n)
printf(" %d", n);
possible outcome:
0 5 6 7 1 8 2 3 4 9.
IA010 9. Concurrency 15
Semaphores
IA010 9. Concurrency 16
Semaphores
• E. Dijkstra, 1965
• a simple mechanism
• based on the concept of guards
• condition + block of code
• allows the code to be executed only if the condition is
fulfilled
• semaphore is an implementation of guard
• semaphore data
• an integer counter + a queue of waiting tasks
• operations
• P (wait ) [probeer te verlagen – try to decrease]
• V (signal/resume ) [verhogen – increase]
• counter values
• 0, 1 – binary (mutex)
• 0 . . . n – counting semaphores
IA010 9. Concurrency 17
Semaphore implementation
wait(s)
if s.counter > 0 then
s.counter--
else
(s.queue).insert(P)
suspend P’s execution
end
signal(s)
if isempty(s.queue) then
s.counter++
else
P = (s.queue).remove()
mark P as ready
end
IA010 9. Concurrency 18
Semaphore example
both competion and cooperation
IA010 9. Concurrency 19
Mutex in C – Linux 2.4.0
static int solo1_midi_release(struct inode *inode, struct file *file)
...
lock_kernel();
if (file->f_mode & FMODE_WRITE) {
add_wait_queue(&s->midi.owait, &wait);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
spin_lock_irqsave(&s->lock, flags);
count = s->midi.ocnt;
spin_unlock_irqrestore(&s->lock, flags);
if (count <= 0) break;
if (signal_pending(current)) break;
if (file->f_flags & O_NONBLOCK) {
remove_wait_queue(&s->midi.owait, &wait);
set_current_state(TASK_RUNNING);
return -EBUSY;
}
...
unlock_kernel();
return 0;
}
IA010 9. Concurrency 20
Semaphores: evaluation
pros
• simple and efficient
problems
• prone to errorneous use
(missing wait or signal)
• deadlocks
IA010 9. Concurrency 21
Monitors
IA010 9. Concurrency 22
Monitors
IA010 9. Concurrency 23
Monitor example
[Sebesta]
IA010 9. Concurrency 24
Concurrency in Java
IA010 9. Concurrency 25
Java Threads
• threads are lightweight tasks
(i.e. sharing the same address space)
• communication using shared data
(and the join method)
Concurrent units
1 run() method of various objects
• descendants of the Thread class
• classes implementing Runnable
2 the main method
class MyThread extends Thread {
public void run() { ... }
}
...
Thread myTh = new MyThread();
myTh.start();
IA010 9. Concurrency 26
The thread class
selected methods
IA010 9. Concurrency 28
Java – mutual exclusion
1 semaphores
• java.util.concurrent.Semaphore
• counting semaphores
2 synchronized methods/blocks
• must be declared synchronized
• each object has its own implicit lock
and a ready task queue
• a synchronized method must first obtain the lock
• monitor = an object with all methods declared
synchronized
class Buffer {
private int [100] buf;
...
public synchronized void deposit(int item) { ... }
public synchronized int fetch() { ... }
...
}
IA010 9. Concurrency 29
Java – cooperation sync.
IA010 9. Concurrency 30
Java atomic variables
IA010 9. Concurrency 31
Java atomic variables IIa
example
class Counter {
private int c = 0;
IA010 9. Concurrency 32
Java atomic variables IIb
example
class SynchronizedCounter {
private int c = 0;
IA010 9. Concurrency 33
Java atomic variables IIc
example
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
IA010 9. Concurrency 34
Java – explicit locks
• an alternative to synchronized
• starting with Java 5.0
• class ReentrantLock, interface Lock
• methods lock, tryLock, unlock
• advantages (compared to synchronized):
• the tryLock method waits only for a specified time
• does not have to follow the nesting structure
IA010 9. Concurrency 35
Message passing
IA010 9. Concurrency 36
Message passing
IA010 9. Concurrency 37
Concurrency in Ada
IA010 9. Concurrency 38
Ada – syntax
Specification
task Task_Example is
entry Entry_1(Item : in Integer);
end Task_Example;
Implementation
task body Task_Example is
begin
loop
accept Entry_1(Item : in Integer) do
...
end Entry_1;
end loop;
end Task_Example;
IA010 9. Concurrency 39
Ada – the course of synchronization
IA010 9. Concurrency 40
Ada – choosing the recipient
• significant asymmetry
• the sending task must know the name of the entry point
• the receiving task receives from anybody
• multiple entry points per task?
• considered in the order they appear
• select clauses – in any order
select
accept Foo_Msg(formal parameters) do
...
end Foo_Msg;
...
or
accept Bar_Msg(formal parameters) do
...
end Bar_Msg;
...
end select;
IA010 9. Concurrency 41
Ada buffer example
task body Buf_Task is
Bufsize : constant Integer := 100;
Buf: array (1..Bufsize) of Integer;
Filled : Integer range 0..Bufsize := 0;
Next_In,Next_Out : Integer range 1..Bufsize := 1;
begin
loop
select
when Filled < Bufsize => -- open or closed
accept Deposit(Item : in Integer) do
Buf(Next_In) := Item;
end Deposit;
Next_In := (Next_In mod Bufsize) + 1;
Filled := Filled + 1;
or
when Filled > 0 => -- open or closed
accept Fetch(Item : out Integer) do
...
end Buf_Task;
IA010 9. Concurrency 42
Ada concurrency
there’s more . . .
• shared memory in addition to message passing
• tasks can be used to implement monitors,
but are much more general!
similar to the relationship between packages and ADTs
IA010 9. Concurrency 43
Concurrency in functional
languages
IA010 9. Concurrency 44
Multilisp
pcall
(pcall f a b c d)
future
(future x)
IA010 9. Concurrency 45
Concurrent ML (CML)
IA010 9. Concurrency 46