Picking Locks

by Kofi Sarfo 18. September 2009 18:35

One fact I forget with consistent regularity is that locks in C# and .NET for that matter are implemented using the System.Threading.Monitor class.

static object moveCountLock = new Object(); private int moveCount; private void IncrementMoveCount() { Monitor.Enter(moveCountLock); moveCount++; Monitor.Exit(moveCountLock); }

And if we were to place the Monitor.Exit in a Finally part of the Try/Catch then effectively it becomes the following:

private void IncrementMoveCount() { lock (moveCountLock) { moveCount++; } }

To put this all in some context, the code above is designed to address race conditions though the MSDN article on Concurrency from which I take this summary elaborates on locks. And whilst we're discussing locks it's worth considering the volatile keyword.

For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock-statement.

Two things worth pointing out here. It turns out the famous Double-Check Locking flaw previously requiring the volatile keyword no longer needs one. At least not if you're using C# but might as well leave it in for Mono and friends, suggests Phil Haack in: Double Check Locking and Other Premature Optimizations Can Shoot You In The Foot.

A few hours worth of reading ahead I think...

Kiva Loans

  • Margret

    Margret

    Personal Housing Expenses

    Requested loan: $625

    Amount raised: $0

    Masindi, Uganda

    to buy iron sheets and doors for her house.

    Loan Now »

  • St Theresa Women Group

    St Theresa Women Group

    Clothing

    Requested loan: $3100

    Amount raised: $0

    Kasese, Uganda

    to buy clothes.

    Loan Now »

  • Zephanus

    Zephanus

    Fish Selling

    Requested loan: $200

    Amount raised: $0

    Kasese, Uganda

    to buy fish to sell.

    Loan Now »

To see more entrepreneurs »

Make a loan to an entrepreneur across the globe for as little as $25. Kiva is the world's first online lending platform connecting online lenders to entrepreneurs across the globe.