C++ – How to open file in exclusive mode in C++

cio

I am implementing some file system in C++. Up to now I was using fstream but I realized that it is impossible to open it in exclusive mode. Since there are many threads I want to allow multiple reads, and when opening file in writing mode I want to open the file in exclusive mode?
What is the best way to do it? I think Boost offers some features. And is there any other possibility? I would also like to see simple example. If it is not easy / good to do in C++ I could write in C as well.

I am using Windows.

Best Answer

On many operating systems, it's simply impossible, so C++ doesn't support it. You'll have to write your own streambuf. If the only platform you're worried about is Windows, you can possibly use the exclusive mode for opening that it offers. More likely, however, you would want to use some sort of file locking, which is more precise, and is available on most, if not all platforms (but not portably—you'll need LockFileEx under Windows, fcntl under Unix).

Under Posix, you could also use pthread_rwlock. Butenhof gives an implementation of this using classical mutex and condition variables, which are present in C++11, so you could actually implement a portable version (provided all of the readers and writers are in the same process—the Posix requests will work across process boundaries, but this is not true for the C++ threading primitives).