Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I unit test for multithreading problems before writing any lock?

I am writing a class that I know that needs a lock, because the class must be thread safe. But as I am Test-Driven-Developing I know that I can't write a line of code before creating a test for it. And I find very difficult to do since the tests will get very complex in the end. What do you usually do in those cases? There is any tool to help with that?

This question is .NET specific

Someone asked for the code:

public class StackQueue
{
    private Stack<WebRequestInfo> stack = new Stack<WebRequestInfo>();
    private Queue<WebRequestInfo> queue = new Queue<WebRequestInfo>();

    public int Count
    {
        get
        {
            return this.queue.Count + this.stack.Count;
        }
    }

    public void Enqueue(WebRequestInfo requestInfo)
    {
        this.queue.Enqueue(requestInfo);
    }

    public void Push(WebRequestInfo requestInfo)
    {
        this.stack.Push(requestInfo);
    }

    private WebRequestInfo Next()
    {
        if (stack.Count > 0)
        {
            return stack.Pop();
        }
        else if (queue.Count > 0)
        {
            return queue.Dequeue();
        }
        return null;
    }
}
like image 266
Jader Dias Avatar asked Apr 26 '09 21:04

Jader Dias


People also ask

Why is testing multithreaded concurrent code so difficult?

Testing a multithreaded application is more difficult than testing a single-threaded application because defects are often timing-related and more difficult to reproduce.

Can multiple threads take a lock simultaneously?

Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

How do I know if multithreading is working?

Run it with -t processor , and compare "Core Count" and "Thread Count" in the output. If these two counts are the same, it means Hyper-Threading is not enabled. If "Thread Count" is twice of "Core Count", it means Hyper-Threading is enabled.


1 Answers

Well, you can usually use things like ManualResetEvent to get a few threads into an expected problem state before releasing the gate... but that only covers a small subset of threading issues.

For the bigger problem of threading bugs, there is CHESS (in progress) - maybe an option in the future.

like image 87
Marc Gravell Avatar answered Oct 08 '22 20:10

Marc Gravell