CodeSOD: Synchronized Threads


Tim was debugging one of those multithreading bugs, where there appeared to be a race condition of some kind. The developer who had initially written the code denied that such a thing could exist: “It’s impossible, I used locks to synchronize the threads!”

Well, he did use locks at the very least.

/// <summary>
/// Performs the synchronisation
/// </summary>
/// <param name="state">Current state</param>
private void Synchronize(object state)
{
    // Take care that this can only run in one thread at a time
    var lockThis = new Object();
    lock (lockThis)
    {
        //…code…
    }
}

There is of course, one problem. The object you use for the lock needs to be shared across threads. This is less a “lock” in the sense of an “air lock” and more a lock in the sense of a “complete hull breach”.


[Advertisement] Manage IT infrastructure as code across all environments with Puppet. Puppet Enterprise now offers more control and insight, with role-based access control, activity logging and all-new Puppet Apps. Start your free trial today!

http://ift.tt/2vnID3F

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s