Sunday, September 15, 2013

Conventional threadsafety

The conventional approach is to use the `lock` keyword to wrap operations that are sensitive to threading.

    class Counter
    {
        readonly object _syncRoot = new object();
        int i = 0;
        internal int GetValue()
        {
            lock (_syncRoot)
            {
                return i++;
            }
        }
    }
It's popular, and there's nothing wrong with it per se, but my goal is to use TDD. I can write a test that motivates the non-lock parts of this code, but I don't know how to write a test that demands the locking.


No comments: