What Every Dev Must Know About Multithreaded Apps

Pay attention to this few lines of code:

class Calculator {
    private static int m_TotalCount;


    public void DailyCut(int
limit)
    {
        m_TotalCount = 0;
        while
(m_TotalCount != 0 && m_TotalCount < limit)
        {
            // some process
            m_TotalCount++;
        }
    }

    // other methods
}

Let's focus in just one of the several silly things of the sample: after setting m_TotalCount to 0, we immediately check whether m_TotalCount is different from zero, which will never be true, so the process inside the loop will never be executed. Obvious, right?

Now, what would you do if you find out that the process, however infrequently, does get executed? A bug in .NET? Bill Gates? Well, far more plausible is that we are facing a concurrency problem: if several execution threads run through the Calculator class, then may be some method inside thread Y changes the value of m_TotalCount, right when thread X is between the assignment and the while, improbable but possible.

This is an example of the bad things that can happen in multi-threaded environments, that's why it is recommended that we rookies better stay away from these waters, but at the same time multi-threaded programming offers several tempting advantages and, besides, with the generalization of multi-core and multi-process machines, it's going to be an unavoidable fact of life. That's why we better learn the ways and means of multi-threading and a good starting point is this nice article by Van Morrison that won an Excellence Award from the Society for Technical Communication. A very short and recommended reading.

17 Comments

Comments have been disabled for this content.