Daniel

Daniel

  • NA
  • 1
  • 0

Reading and Updating a File

Apr 26 2008 3:10 AM
Hi, I'm doing a simple piece of code that caches files. If the client (via HTTP) asks for a file and it's not recent enough, the code fetches it again (from another HTTP source). The issue is that:
  1. I don't want to be updating and reading the file at the same time (because it might be incomplete).
  2. If the file is not being updated, multiple threads can read the file at the same time.
The easy solution is to just lock on a thread monitor (a shared object) for both reading and updating. But I don't want to do that, because I don't want reads to wait on each other. I want reads to wait for the write.

I've thought about doing this:

object monitor = sharedMonitor;
if (monitor == null)
   monitor = new object(); // then we don't lock
lock (monitor) {
    read();
}

and so I set the sharedMonitor if I'm updating, but this is risky too (because other code might be reading already).

How can I lock BETWEEN two methods while letting one of the methods multithread happily? I realize that this question is somewhat academic, but the application is going to be used by billions of users someday.

Thanks,
D. Rosenstark