51.9 File Locking Strategies
File locking is a critical mechanism for coordinating access to shared resources in a multi-process environment. It prevents the classic “lost update” problem, where multiple processes or threads overwrite each other’s changes to the same file, leading to data corruption or inconsistency. Unlike database systems that typically provide built-in concurrency control, file-based applications must implement their own locking strategies using operating system primitives. The fundamental purpose of file locking is to establish a protocol where a process can acquire exclusive or shared rights to specific regions of a file or the entire file, temporarily preventing other processes from making conflicting modifications. It’s crucial to understand that file locks are advisory on most Unix-like systems (Linux, macOS) and mandatory on Windows. Advisory locks are more like signals between cooperating processes—they only work if all processes attempting to access the file explicitly check for locks. A process ignoring these checks can freely read or write to a locked file. Mandatory locks, however, are enforced by the operating system kernel, which will prevent any access that violates an existing lock, regardless of whether the process attempts to check for it.