Search code examples
c++boostfile-locking

Looking for the best boost file lock mechanism for writers - readers


I have files residing in different directories as follows:

\201603\30
           file_1
           file_2
\201603\31
           file_3
           file_4
           file_5

There are 2 writers & 2 readers and they are all threads in my program.

Lock will be applied on directory not individual files (e.g. \201603\30 or \201603\31).

I would like to use boost library to make my program portable.

I have searched and been introduced to boost::interprocess::file_lock. I was just wondering that do I really need an 'interprocess' lock here, and is that lock sharable between readers? Do you have any suggestions other than boost::interprocess::file_lock?


Solution

  • Since all lock users in are in your program, what do you need interprocess locking for? file_lock puts the mutex into a file which lets the kernel manage locking/unlocking. This is only useful if multiple processes need to respect the lock.

    It sounds like you need nothing more than a regular read-write lock, which Boost calls shared_lock. See this answer for an example on how to use one: https://stackoverflow.com/a/989816/321772

    In summary, a shared lock lets multiple threads acquire the lock for reading, but only allows one thread to upgrade the lock to a writer (excludes all other readers/writers).