package main
import (
"fmt"
"sync"
"os"
"time"
"golang.org/x/sys/unix"
)
func main() {
file, err := os.Open("/home/testfile")
if err != nil {
fmt.Println("create failed")
return
}
defer file.Close()
if err = unix.Flock(int(file.Fd()), unix.LOCK_EX); err != nil {
fmt.Println("flock failed 2")
}
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
if err = unix.Flock(int(file.Fd()), unix.LOCK_EX); err != nil {
fmt.Println("flock faild 3")
}
fmt.Println("lock success")
time.Sleep(3*time.Second)
wg.Done()
}()
go func() {
if err = unix.Flock(int(file.Fd()), unix.LOCK_EX); err != nil {
fmt.Println("flock faild 3")
}
fmt.Println("lock success")
time.Sleep(time.Second)
wg.Done()
}()
wg.Wait()
return
}
按照书上说应该会互斥,为啥我运行的时候flock无法做到互斥,每个goroutine就能很快正常执行?