Earlier today I was debugging something that went a bit like this:
class Foo {
void AccessCriticalSection() {
try {
if (IO.File.Exists("\\path\to\lock.txt")
throw new Exception();
System.IO.File.Create("\\path\to\lock.txt");
criticalSection();
} catch (Exception ex) {
// ignored
}
}
void CriticalSection() {
// banana banana banana
System.IO.File.Delete("\\path\to\lock.txt");
}
}
Let's not even get into how terrible this is… but it's essentially trying to use a file called lock.txt
as its mutex. The operation isn't atomic, other processes are just not getting through the critical section if another process is using it (they're intended to be able to continue after the lock is released if you can believe it), etc. etc. Obviously it needs to be fixed.
How do I properly obtain a lock to synchronize access to the filesystem across multiple processes? The processes are multiple instances of the same process, so they can share some protocol rather than specifically locking the directory (i.e., they can easily use what is the equivalent to all instances of some class locking on something like private final static Object lock = new Object();
to synchronize access to static methods)