Programming Assignment 1 posted soon
A CounterExample Mystery!
What happens when multiples threads call increment()?
public void increment () {
++count;
}
Program: sequence of instructions to be carried out by a computer
Process: a computing entity that can carry out instructions specified in a program
Execution: a sequence of operations performed by a set of processes
Random Access Machine (RAM) model interactions:
Counter object is stored in memory
Counter stores a value count
CountThread instructions stored in memoryCounterThread is executed, it follows these instructionsfor (long i = 0; i < times; i++) {
counter.increment();
}
public void increment () { ++count; }
What are CPU/Memory interactions when counter.increment() is executed?
public void increment () { ++count; }
Modern computers:
Parallel Random Access Machine (PRAM)
read(i) and write(i, val)
read/write operations are atomic
Nondeterminism:
if multiple threads access same memory location concurrently all “consistent” outcomes are possible
two processes call write(i, a) and write(i, b)
one process calls read(i) another write(i, a)
increment operationincrement same Counter concurrentlypublic void increment () { ++count; }
Suppose: count = 7 & two threads both call increment() concurrently
What are the possible executions? What are possible outcomes/results?
PRAM model allows for all processes to access/modify all memory
Each thread can have variables that only it accesses
public class CounterThread implements Runnable {
private Counter counter; private long times;
public CounterThread (Counter counter, long times) {
this.counter = counter; this.times = times;
}
public void run () {
for (long i = 0; i < times; i++) {
counter.increment();
}
}
}
void increment(int[] a) {
int i = 0;
while (i < a.length) {
a[i] = a[i] + 1;
i = i + 1;
}
}
If a = [0, 0, 0, 0] and two threads, what are possible outcomes?
void increment(int[] a) {
int i = 0;
while (i < a.length) {
a[i] = a[i] + 1;
i = i + 1;
}
}
If a = [0, 0, 0, 0] and $k$ threads, what are possible outcomes?
void increment(int[] a) {
int i = 0;
while (i < a.length) {
a[i] = a[i] + 1;
i = i + 1;
}
}
How could we fix the problem of mis-counting?