Friday, March 17, 2017

Concurrency

Why do one thing at a time if you can do many things at a time? That's what multi-core processors allow computers to do - do many things in parallel. Even in single processors, from the users perspective it still seems as if things are running in parallel because operating systems are so damn good at context switching.

A thread is the fundamental unit of execution in a computer. It starts somewhere and ends somewhere. Once you introduce multiple threads of executions, you can open up a whole can of synchronization problems if you don't synchronize your threads!

For example, lets say Sally and Bob share a bank account. The way the system works is that there is a number of ATM machines in different locations that are connected to the central banking system. When someone initiates a transaction, a new thread of execution is initiated in the program that runs in the central system.

In this program, lets say there are accounts (one of which is shared by Bob and Sally).

The code involved in updating the balance as a result of a deposit is as follows:

newBalance = userBalance - amount (the calculation)
userBalance = newBalance (the update)

Now lets say Bob and Sally both attempt to withdraw at the same time. Lets say Thread A is the thread initiated by Bob and Thread B is initiated by Sally.

1. Bob and Sally both initiate a withdrawal of $100 from a starting balance of $500.
2. Thread A calculates the new balance to be $400 and then gets suspended while Thread B is run. At this point, the user balance is still $500.
3. Thread B ALSO calculates the new balance to be $400 and then goes to completion.
4. Tread A finishes with balance of $400.

They both withdraw $100, but the final balance is $400 :)

Luckily, there are several ways to synchronize threads so that things like this don't happen. A common construct is a semaphore which basically protects shared resources. So if one was used in this situation, it would be used to protect the account resource. If someone is already using the account to withdraw or deposit, don't let anyone (any other thread) access it.

No comments:

Post a Comment