Finding Callers of Thread-Unsafe Functions

about | archive


[ 2006-December-14 23:22 ]

Let's imagine that you have some sort of weird bug that you think might be caused by someone calling a function that is not thread-safe from two threads. How can you figure out if this is happening? I had a bug like this recently, and I decided to crash my program when this happens. How? I added a lock to the method which is acquired at the beginning and released at the end. Then, I crashed the program if the lock could not be acquired, since that would indicate that another thread was using it. Here is an example (complete Java example):

class Foo {
    Lock mutex;

    void unsafeMethod() {
        if (!mutex.tryLock()) {
            // There is someone in this thread: crash to get a stack trace
            crashAndDumpStacks();
        }

        // ... method body ...

        mutex.Unlock();
    }
};

This rapidly caused a nice crash when more than one thread was in the method, and the stack showed how the callers got there. Sadly, this won't work if the problem is rare. Running the program in a loop might help.

This trick could actually be applied more broadly. I imagine it would be possible to have a debug build where any function not flagged as being thread-safe could have this type of runtime check. It would slow things down, but it would be simple technique for preventing thread-safety bugs.