A concurrent execution is linearizable if:
An implementation of an object is linearizable if:
public class Counter {
int count = 0;
public void increment () {
++count;
}
public int read () {
return count;
}
}
Why is this bad with multiple threads, even if read/write operations are atomic?
For two threads:
public class TwoCounter {
int[] counts = new int[2];
public void increment (int amt) {
int i = ThreadID.get(); // thread IDs are 0 and 1
int count = counts[i];
counts[i] = count + amt;
}
public int read () {
int count = counts[0];
count = count + counts[1];
return count;
}
}
Is this better?
TwoCounter
Linearizable?public class TwoCounter {
int[] counts = new int[2];
public void increment (int amt) {
int i = ThreadID.get(); // thread IDs are 0 and 1
int count = counts[i];
counts[i] = count + amt;
}
public int read () {
int count = counts[0];
count = count + counts[1];
return count;
}
}
public class ThreeCounter {
int[] counts = new int[3];
public void increment (int amt) {
int i = ThreadID.get(); // thread IDs are 0, 1, and 2
int count = counts[i];
counts[i] = count + amt;
}
public int read () {
int count = counts[0];
count = count + counts[1];
count = count + counts[2];
return count;
}
}
Is ThreeCounter
Linearizable?
ThreeCounter
Linearizable?You will work through more problems on linearizability on Homework 3 and Quiz 3.