December 14, 2007

Threading is Hard

Here's to another obvious title. Even in .Net, where they have done a lot to simplify things (thank-you background worker), however threading always seems to cause the biggest headaches even when just coding things. Usually if you ignore the issues with threading there are random crashes in testing, but as you design the code you sit there and try to think about what you want to do. First, there are very few references on threading in .Net. Secondly, all the tutorials that there are involve simple things like launching a bunch of threads that sleep, and output their thread id to the console. Or they are examples of how to update the UI from a background thread. Not to pick on these, but there never seems to be any examples of how to interact with real objects in your application in a thread. What requires a lock, and what doesn't? How do I make my own classes threadsafe without locking entire classes of functions. And then how do I ensure I don't end up with deadlock in my applications (this tends to be one of those things that only show up when the application is under the kind of load it never is either in testing or in development). One of the few really good resources on threading in C# was this article, which lead me to buy the book C# 3.0 In A Nutshell and I was very glad I did.

But enough whinging and complaining about how difficult threading is, that is, as they say, why we get paid the big bucks. Here are my suggestions to make it easier, use Attributes to declare which functions have the potential of being used in multiple threads and then have the compiler throw a warning on the access of potentially non-threadsafe variable usage. This is the kind of thing that compilers are good at, and is the kind of thing that programmers suck at. If Microsoft decides not to include this, why not a company like JetBrains add it to Resharper. Another thing that might be done is exposing in intellisense whether or not an object is thread safe. That's it, that's all, until the next time I have to debug some obscure bug due to some unprotected variable that somehow got accessed on multiple threads, at which point I will come back and curse threading again...