Program Vs Process Vs Thread
Program Vs Process Vs Thread
A program is a set of instructions and associated data that resides on the disk
and is loaded by the operating system to perform some task. An executable file
or a python script file are examples of programs. In order to run a program,
the operating system's kernel is first asked to create a new process, which is an
environment in which a program executes.
Process
Note a program or a process are often used interchangeably but most of the
times the intent is to refer to a process.
Counter Program
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
Add one to the value just read
Store the newly computed value back to the register
Lets call one thread as T1 and the other as T2. Say the counter value is equal
to 7.
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.
Since the execution of the threads can't be predicted and is entirely up to the
operating system, we can't make any assumptions about the order in which
threads get scheduled and executed.
Thread Unsafe Class
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);
}
}