2 Program Vs Process Vs Thread
2 Program Vs Process Vs Thread
This lesson discusses the differences between a program, process and a thread. Also included is an example of a
thread-unsafe program.
Program
Process
Thread
special attention needs to be paid when any thread tries to read or write
to this global shared state. There are several constructs offered by various
programming languages to guard and discipline the access to this global
state, which we will go into further detail in upcoming lessons.
Notes
1. int counter = 0;
2.
3. void incrementCounter() {
4. counter++;
5. }
Read the value of the variable counter from the register where it is
stored
Now imagine if we have two threads trying to execute the same function
incrementCounter then one of the ways the execution of the two threads
can take place is as follows:
Lets call one thread as T1 and the other as T2. Say the counter value is
equal to 7.
3. T2 gets scheduled and luckily gets to complete all the three steps A, B
and C before getting switched out for T1. It reads the value 7, adds
one to it and stores 8 back.
4. T1 comes back and since its state was saved by the operating system,
it still has the stale value of 7 that it read before being context
switched. It doesn't know that behind its back the value of the
variable has been updated. It unfortunately thinks the value is still 7,
adds one to it and overwrites the existing 8 with its own computed 8.
If the threads executed serially the final value would have been 9.
import java.util.Random;
class DemoThreadUnsafe {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
badCounter.increment();
DemoThreadUnsafe.sleepRandomlyForLessThan10Secs();
}
}
});
@Override
public void run() {
for (int i = 0; i < 100; i++) {
badCounter.decrement();
DemoThreadUnsafe.sleepRandomlyForLessThan10Secs();
}
}
});
class ThreadUnsafeCounter {
int count = 0;
void printFinalCounterValue() {
System.out.println("counter is: " + count);
}
}