在Golang中操作INI文件并加锁可以使用sync.Mutex
来实现。下面是一个示例代码:
package main
import (
"fmt"
"github.com/go-ini/ini"
"sync"
)
var mutex sync.Mutex
func writeINIFile(filename string, content string) {
mutex.Lock()
defer mutex.Unlock()
cfg, err := ini.Load(filename)
if err != nil {
fmt.Println("Failed to load INI file:", err)
return
}
section, err := cfg.GetSection("Section")
if err != nil {
fmt.Println("Failed to get section from INI file:", err)
return
}
key := "key"
value := "value"
err = section.ReflectFrom(&struct{ Key string }{Key: value})
if err != nil {
fmt.Println("Failed to reflect key-value into section:", err)
return
}
err = cfg.SaveTo(filename)
if err != nil {
fmt.Println("Failed to save INI file:", err)
return
}
fmt.Println("INI file written successfully.")
}
func main() {
filename := "config.ini"
content := "[Section]\nkey=value"
writeINIFile(filename, content)
}
在这个示例中,我们创建了一个名为mutex
的全局互斥锁变量,并在写入INI文件之前使用mutex.Lock()
进行加锁操作,然后使用defer语句添加了解锁操作mutex.Unlock()
。
注意:该示例使用了第三方库 github.com/go-ini/ini
来操作INI文件。请确保先安装该库:go get github.com/go-ini/ini
这样就可以通过互斥锁来保证在多个goroutine同时访问INI文件时的安全性。只有获取锁的goroutine才能执行写入操作,其他goroutine需要等待解锁后才能继续执行。
内容由零声教学AI助手提供,问题来源于学员提问