
Golang Flock is a synchronization primitive that allows you to lock a file or a set of files, preventing other processes from accessing them until the lock is released.
To use Golang Flock, you need to import the "syscall" package and use the Flock function to acquire a lock on a file descriptor. This function takes two arguments: the file descriptor and the operation to perform.
Acquiring a lock on a file is essential in concurrent programming to prevent data corruption and ensure consistency. Golang Flock provides a way to achieve this in a thread-safe manner.
Golang Flock supports both exclusive and shared locking modes. Exclusive locking prevents other processes from accessing the file, while shared locking allows multiple processes to read the file simultaneously.
Flock Types
Golang flock supports two types of flocks: advisory and mandatory.
Advisory flocks allow a process to request exclusive access to a resource, but do not prevent other processes from accessing it.

Mandatory flocks, on the other hand, prevent other processes from accessing the resource while it is locked.
A process can use flock to lock a file, allowing it to be the only process modifying it at a given time.
Flock is a portable and efficient way to implement locking in Golang.
Flock Functions
Flock Functions are a crucial part of Go's file locking mechanism.
The fcntl system call allows you to operate on file descriptors, and the flock function is used to acquire file locks. You can specify a flock structure as an argument to the fcntl system call to lock a file.
Flock functions can be categorized into three types: F_SETLK, F_SETLKW, and F_GETLK. Here's a brief overview of each:
- F_SETLK: This function attempts to acquire a lock on a file in a non-blocking manner. If the lock cannot be acquired, it returns an EACCES or EAGAIN error.
- F_SETLKW: This function attempts to acquire a lock on a file, blocking until the lock can be acquired.
- F_GETLK: This function retrieves information about the lock on a file.
These functions are standardized under POSIX and can be used to achieve advisory or mandatory locks on files.
Locked
The Locked function is a way to check the current lock state of a Flock object. It returns true if the lock is locked, and false if it's unlocked.
If you call Locked on a Flock object that's already shared-locked, it will short-circuit and return immediately. This is because it assumes it can take the mutex lock.
The Locked function is useful for checking the current lock state, but be aware that the state may have changed by the time you use the returned value.
Fcntl
Fcntl is a system call that allows you to operate on file descriptors.
It's used to acquire file locks, which can be specified in a range of bytes within the file.
The basic type of lock is an advisory lock, but you can also use a mandatory lock if you try hard enough.
These locks are standardized under POSIX.
Here are some of the commands you can use with fcntl to manipulate file locks:
- F_SETLK: Acquires a lock non-blocking, returning EACCES or EAGAIN if the lock cannot be acquired.
- F_SETLKW: Acquires a lock, blocking until the lock can be acquired if necessary.
- F_GETLK: Retrieves information about the lock.
There are two types of locks: F_RDLCK and F_WRLCK, which are specified in the flock structure, similar to the behavior of sync.RWMutex in Go.
You can also use F_UNLCK to unlock the file.
Blocking
Blocking is a crucial aspect of flock functions, and one key method is LockBlocking. This method acquires an exclusive filesystem lock for a given path.
If the lock is already held, LockBlocking will repeatedly attempt to acquire it using the supplied Blocker in between attempts. This ensures that the lock is obtained eventually, even if it's held by another entity.
LockBlocking is a convenience method for L's Lock, making it a useful tool for developers.
Broaden your view: Golang Method
Flock Usage
fcntl and flock are two system calls in Linux that allow for file locking.
Both fcntl and flock locks are treated as separate locks within the kernel, but using both in a single program can lead to issues on some systems, so it's recommended to use only one.
Using flock for file locking is a common approach, but it's worth noting that flock and fcntl can have different effects on some systems.
In this section, we'll focus on using fcntl for demonstration purposes.
Flock System Calls

Flock System Calls are a way to achieve file locking in Linux, and they're implemented using two system calls: fcntl and flock. The two types of locks obtained through these system calls are treated as separate entities within the kernel, but using both in a single program can lead to conflicts, so it's recommended to stick with one or the other.
The flock system call is a more straightforward way to achieve file locking, and it's the one we'll be using for our demonstration.
In POSIX systems, including Go, the flock system call is implemented using the syscall.Flock() function. This function takes two arguments: the file descriptor of the file to be locked, and a flag indicating the lock mode.
The flag can take one of the following values:
It's worth noting that the flock system call is not available on Windows, where the LockFileEx() function is used instead.
Flock Implementation
In Linux, you can achieve file locking using the fcntl and flock system calls.
Both fcntl and flock acquire different types of locks that are treated separately within the kernel, but using only one of them in a single program can simplify the code and avoid potential issues with flock and fcntl affecting each other on certain systems.
To implement file locking in Go, we'll focus on fcntl as our example, since the discussion about both fcntl and flock is common ground.
In our case, using fcntl will be the way to go, so let's explore how to use it to achieve file locking.
Flock Usage in Go
In Go, you can use the syscall package to achieve file locking through syscall.FcntlFlock() and syscall.Flock(). However, these are just system calls wrapped in the Go standard library, so you'll need to add a timeout feature yourself.
The syscall.Flock() function is non-blocking, which means it will immediately return without waiting for the lock to be acquired. To implement a timeout, you'll need to use a loop that repeatedly calls syscall.Flock() with a retry delay.
Some popular Go libraries for file locking with timeouts include github.com/gofrs/flock and github.com/jviney/go-filelock. However, these libraries also have their own limitations.
For your interest: Golang Syscall
TryRContext
TryRLockContext is a function that repeatedly tries to take a shared lock until one of the conditions is met. This function is available in the flock package and is used to acquire a shared lock on a file.
The TryRLockContext function takes a context.Context as an argument, which allows you to specify a timeout or cancellation. If the context is cancelled or the timeout is reached, the function will return an error.
Here are some key facts about TryRLockContext:
- It repeatedly tries to take a shared lock until one of the conditions is met.
- It takes a context.Context as an argument, which allows you to specify a timeout or cancellation.
- If the context is cancelled or the timeout is reached, the function will return an error.
TryRLockContext is a non-blocking function, meaning it will not block the execution of the program if it is unable to acquire the lock. Instead, it will return false to indicate that the lock was not acquired.
The TryRLockContext function is designed to be used in situations where you need to acquire a shared lock on a file, but you don't want to block the execution of the program if the lock is not available. It is a convenient and efficient way to handle shared locking in Go.
Close Added Inv0.6.0
In Go, the Flock type has a Close method that was added in version 0.6.0.
The Close method is equivalent to calling Unlock. This means it releases the lock and closes the underlying file descriptor.
It's essential to note that Close does not remove the file from disk. That's up to your application to handle.
By calling Close, you're essentially releasing the lock on the file, allowing other processes to access it if needed.
Recommended read: Golang Close
Remove
Removing a lock can be a bit tricky in Go, especially when working with the Flock type. The Lock function will wait until it can obtain an exclusive file lock, but it's recommended to use TryLock() instead to avoid blocking.

If you're already exclusive-locked, Lock will return immediately, assuming it can take the mutex lock. This can be a gotcha if you're not paying attention.
Be careful when using exclusive locks in conjunction with shared locks (RLock), because calling Unlock() may accidentally release the exclusive lock that was once a shared lock. This can happen on UNIX-like operating systems where a shared lock can be transparently replaced with an exclusive lock.
Added in 0.4.0
Added in 0.4.0, the Flock package in Go gained two new functions: RLocked and TryRLock. RLocked returns the read lock state, indicating whether the file is locked or unlocked. This function is useful for checking the lock status without blocking.
RLocked returns a boolean value, true if the file is locked and false if it's unlocked. This can be useful for debugging or logging purposes.
TryRLock is a non-blocking function that attempts to take a shared file lock. If the lock is available, it will be acquired without blocking, and the function will return true. If the lock is already held by another goroutine, the function will return false instead of waiting for the lock. This is useful for concurrent programming, where you need to check if a lock is available before attempting to acquire it.
Here's a quick reference to the two new functions:
How to Interrupt Flock

To interrupt a flock, you can use signals. This is because blocking system calls return with EINTR when a signal happens, allowing you to implement timeouts.
Most blocking system calls, including flock, are interruptible by signals. This means you can send a signal to the process holding the lock, causing it to return with an EINTR error and allowing you to acquire the lock.
By sending a signal, you can implement a timeout or interrupt the flock. This is a common approach to handling file locks in Go.
Unlock
The Unlock function is a crucial step in interrupting a flock. It takes a RW-mutex lock, so while it's running, the Locked() and RLocked() functions will be blocked.
This function short-circuits if you're already unlocked. If not, it calls syscall.LOCK_UN on the file and closes the file descriptor.
It doesn't remove the file from disk, so it's up to your application to do that. The file will still exist after unlocking.
If your shared lock became an exclusive lock, calling Unlock may unintentionally drop the exclusive lock if the consumer believes they have a shared lock.
どうやってファイルロックを中断するか
To interrupt a file lock, you can send a signal to the process holding the lock, causing it to return with an EINTR error.
The solution lies in using signals to interrupt the blocking file lock. Most blocking system calls return with EINTR when a signal happens.
You can use alarm to implement timeouts for system calls, which is a common approach in the context of timeouts.
By sending a signal to the process holding the lock, you can cause the lock to be interrupted and return with an EINTR error.
This is a reliable way to implement file lock timeouts and interruptions.
Featured Images: pexels.com


