Skip to content
This repository was archived by the owner on May 31, 2025. It is now read-only.

Commit 5952c41

Browse files
committed
feat(lock): init lock
1 parent 7c4995a commit 5952c41

File tree

4 files changed

+2067
-0
lines changed

4 files changed

+2067
-0
lines changed

lock/filelock/filelock.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package filelock
2+
3+
import (
4+
"os"
5+
"syscall"
6+
)
7+
8+
type FileLock struct {
9+
f *os.File
10+
}
11+
12+
func New(fp string) (*FileLock, error) {
13+
f, err := os.Open(fp)
14+
if err != nil {
15+
return nil, err
16+
}
17+
return &FileLock{f: f}, nil
18+
}
19+
20+
func (l *FileLock) Lock() error {
21+
err := syscall.Flock(int(l.f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
22+
if err != nil {
23+
return err
24+
}
25+
return nil
26+
}
27+
28+
func (l *FileLock) Unlock() error {
29+
defer l.f.Close()
30+
return syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
31+
}

lock/filelock/filelock_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package filelock
2+
3+
import (
4+
"os"
5+
"sync"
6+
"testing"
7+
8+
"github.com/spf13/cast"
9+
)
10+
11+
func TestFileLock(t *testing.T) {
12+
wg := sync.WaitGroup{}
13+
for i := 0; i < 1000; i++ {
14+
wg.Add(1)
15+
go func(num int) {
16+
defer wg.Done()
17+
flock, _ := New("testdata/config")
18+
err := flock.Lock()
19+
if err != nil {
20+
t.Error(err)
21+
}
22+
defer flock.Unlock()
23+
24+
f, _ := os.OpenFile("testdata/config", os.O_APPEND|os.O_WRONLY, 0666)
25+
defer f.Close()
26+
f.WriteString("test" + cast.ToString(num) + "\n")
27+
}(i)
28+
}
29+
wg.Wait()
30+
}

0 commit comments

Comments
 (0)