C# Rambling : locks

May 02, 2008 16:56

I've been working with C# at work. It's not a far cry from Java, but it seems a little unpolished. Some things work great, others seem pretty primitive. One thing that struck me today was locks.

If you've ever done any thread programming, you know what a Pandora's box they can be. By enabling multiple pieces of code to run at once you skip the problem of a quick function waiting for an unrelated slow function to finish, but you have to worry about more than one piece of code accessing something that shouldn't be shared at once.

The lock command in C# is just the sort of high-level language solution I was hoping for. You tell the runtime that you're not going to be a nice boy and share anymore, do your business, then let go of the lock. If multiple threads execute the same code, the lock will prevent them from doing so simultaneously.

Then comes the interesting question of which object to lock. If you've got something like a file pointer thats fine, but if not then what do you lock? Well, you can lock(this) (as long as it's not in a static method), but that causes a problem if someone creates an instance of your class and locks it.

Interestingly, strings are immutable in C#, and the runtime saves time my not allocating space for new strings if an identical one already exists in memory. It simply points the new string at the existing one. This means that you can lock on a string VALUE (not just a string object) since all strings with that value are the in fact the same. However, this is the very reason why you should NOT do this, as any other string in memory (not just for this class, but for the whole process) could lock the same string and muck with your code.

The way to lock arbitrary code is to create a private dummy object that no one else can see and lock that. That way, no one else can put a lock on your object and bring your code to a halt.

class MyClass{
private object dummy_locker = new object();
public void MyMethod(){
lock(dummy_locker){
//do something
}
}
}

Since this solves one little problem I was having, I'm glad it was such a simple solution.

coding

Previous post
Up