BCS
BCS

Reputation: 78516

Non threadlocked Mutex

This is an offshoot of this question but with a few constraints removed.

I have a system where I need to manage file locking. I need to be able to lock a file (shared read locking) in one thread and then unlock it in another. More accurately, I can't be sure what thread it will be unlocked in or even if the creating thread is still around.

I will also need exclusive write locking to go with this but that will be all in the same thread.

the .NET Mutex won't work as it does extra stuff when the creating thread exits

Upvotes: 0

Views: 457

Answers (3)

Brian ONeil
Brian ONeil

Reputation: 4339

The question that you linked to is crossing process boundaries, but from what I read you are only crossing threads... with this in mind I think that Jeff Richter's ReaderWriterGate class might fit your problem well. It allows you to control access to a shared resource and queue access requests to the resource. It doesn't seem to have any thread affinity so if you are not crossing process boundaries you it might be a solution for you.

Here is a link to an article about the class... Concurrent affairs and you can download the PowerThreading Library from here

If your case is really simple (except for the locking from one thread and releasing from another) I don't see why you couldn't use the built in ReaderWriterLock in .NET (although the one in the PowerThreading library is supposed to be much faster). The Monitor class has no thread affinity and can be accessed from any context so depending on how you are using it this may be your most straight forward solution.

Upvotes: 1

Jezzletek
Jezzletek

Reputation: 113

Sounds to me like a Turnstile problem. You need to manage the readers going in with the first one locking the file and the last one to leave unlocking the file. You can use a semaphore to implement this. You can give preference to the writer by having the turnstile deny readers while there is a writer waiting.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062600

Maybe a (named) Semaphore with a count of one? WaitOne to lock, Release to unlock?

Upvotes: 1

Related Questions