search
HomeBackend DevelopmentGolangHow to implement file lock in golang

How to implement file lock in golang

Dec 19, 2022 am 11:03 AM
golanggo language

In golang, you can use the API of the sync package to implement file locking. File lock (flock) is an advisory lock for the entire file; that is, if a process places a lock on a file (inode), other processes can know it (advisory locks do not force processes to comply); file locks The calling syntax is "syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)".

How to implement file lock in golang

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

When we use Go language to develop some programs, multiple processes often operate on the same file at the same time, which can easily lead to confusion of the data in the file. At this time, we need to use some means to balance these conflicts, and file lock (flock) came into being. Let's introduce it below.

For flock, the most common example is Nginx. After the process runs, the current PID will be written to this file. Of course, if this file already exists, that is, the previous process has not exited, then Nginx It will not restart, so flock can also be used to detect whether the process exists.

flock is an advisory lock for the entire file. In other words, if a process places a lock on a file (inode), other processes can know it (advisory locks do not force processes to comply). The best part is that its first parameter is a file descriptor, and when this file descriptor is closed, the lock is automatically released. When the process terminates, all file descriptors will be closed. So often there is no need to consider things like unlocking atomic locks.

Before introducing it in detail, let’s introduce the code first

package main
import (
    "fmt"
    "os"
    "sync"
    "syscall"
    "time"
)
//文件锁
type FileLock struct {
    dir string
    f   *os.File
}
func New(dir string) *FileLock {
    return &FileLock{
        dir: dir,
    }
}
//加锁
func (l *FileLock) Lock() error {
    f, err := os.Open(l.dir)
    if err != nil {
        return err
    }
    l.f = f
    err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
    if err != nil {
        return fmt.Errorf("cannot flock directory %s - %s", l.dir, err)
    }
    return nil
}
//释放锁
func (l *FileLock) Unlock() error {
    defer l.f.Close()
    return syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
}
func main() {
    test_file_path, _ := os.Getwd()
    locked_file := test_file_path
    wg := sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(num int) {
            flock := New(locked_file)
            err := flock.Lock()
            if err != nil {
                wg.Done()
                fmt.Println(err.Error())
                return
            }
            fmt.Printf("output : %d\n", num)
            wg.Done()
        }(i)
    }
    wg.Wait()
    time.Sleep(2 * time.Second)
}

When running the above code under Windows system, the following error will appear:

How to implement file lock in golang

This is because Windows systems do not support pid locks, so we need to run the above program normally under Linux or Mac systems.

The above code demonstrates starting 10 goroutines at the same time, but during the running of the program, only one goroutine can obtain the file lock (flock). Other goroutinue will throw exception information after failing to obtain flock. This can achieve the effect of allowing only one process to access the same file within a specified period.

The specific call of the file lock in the code:

syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)

We use syscall.LOCK_EX, syscall.LOCK_NB, what does this mean?

flock is a advisory lock and is not mandatory. One process uses flock to lock the file, and the other process can directly operate the file being locked and modify the data in the file. The reason is that flock is only used to detect whether the file is locked. If the file is already locked, another process In the case of writing data, the kernel will not block the write operation of this process, which is the kernel processing strategy of advisory locks.

flock has three main operation types:

  • LOCK_SH: Shared lock, multiple processes can use the same lock, often used as a read shared lock;

  • LOCK_EX: Exclusive lock, only allowed to be used by one process at the same time, often used as a write lock;

  • LOCK_UN: Release the lock.

When a process uses flock to try to lock a file, if the file is already locked by another process, the process will be blocked until the lock is released, or the LOCK_NB parameter is used when calling flock. When trying to lock the file, it is found that it has been locked by another service, and an error will be returned with the error code EWOULDBLOCK.

Flock lock release is very unique. You can call the LOCK_UN parameter to release the file lock, or you can release the file lock by closing fd (the first parameter of flock is fd), which means flock will It is automatically released when the process is closed.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of How to implement file lock in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools