Stu Smith: Making It Up As I Go Along“ My life working for BinaryComponents, coding, design, and other stuff. ”
Last article I talked about the use of locks to solve threading issues, and how they problematic they are: necessary, but very low level. In this article, I'm going to imagine a different world...
Let's imagine that we can open a transaction, just as we might when using SQL, but for ordinary variables. Transactions have two important properties:
And afterall, that consistency is what we're trying to achieve with locking. If we can get transactions working, we should be able to use them instead of locks.
So let's imagine that this exists for memory, not just SQL databases. Our bank account problem from the previous article suddenly becomes very easy to solve:
class BankAccount
{
public void Deposit( long change )
{
BEGIN TRANSACTION
_amount += change;
COMMIT TRANSACTION
}
private t_long _amount;
}
public static void Transfer( BankAccount a, BankAccount b, long amount )
{
BEGIN TRANSACTION
a.Deposit( -amount );
b.Deposit( amount );
COMMIT TRANSACTION
}
Easy. Of course, we could never have that actual syntax in C#, but that's conceptually what we want to achieve.
Of course, one correct (but really bad) way of implementing this would be to have a single, global, lock, and to lock and unlock that as we enter and exit transactions. If we also checked that we were in a transaction before accessing a variable (and that's why I've changed the type to be "t_long" to imply that), then we have solved all three problems mentioned previously. Of course, that method doesn't scale very well: any contention on the lock, even if it was on different values, would block all other threads. It does at least demonstrate that the concept is good.
So next article I'm going to describe a better way of implementing memory-transactions using optimistic locking. I'll also look into the transaction command I've not mentioned so far, ROLLBACK, and discover it's really useful. I have an actual working implementation of all this in C#, so at the end of these articles, I'll make the source available.