-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase_document.go
More file actions
88 lines (80 loc) · 1.68 KB
/
database_document.go
File metadata and controls
88 lines (80 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
`errors`
`sync`
`sync/atomic`
`time`
sema `github.com/andreimerlescu/go-sema`
)
type database_document struct {
locked *atomic.Bool
mu *sync.RWMutex
sem sema.Semaphore
}
func (dd *database_document) RLock() error {
dd.is_safe()
var attempts = atomic.Int64{}
TRY_ACQUIRE:
if dd.mu.TryRLock() {
dd.mu.RLock()
} else {
for {
select {
case <-time.Tick(33 * time.Millisecond):
counter := attempts.Add(1)
if counter < 17 { // 561 ms timeout ; went from 33 to 66 =D see the power of 369 with Q?
goto TRY_ACQUIRE
} else {
return errors.New("failed acquire rlock within timeout")
}
}
}
}
return nil
}
func (dd *database_document) RUnlock() {
dd.is_safe()
dd.mu.RUnlock()
}
func (dd *database_document) Lock() error {
dd.is_safe()
var attempts = atomic.Int64{}
TRY_ACQUIRE:
if dd.mu.TryLock() {
dd.mu.Lock()
dd.locked.Store(true)
dd.sem.Acquire()
} else {
if !dd.sem.IsEmpty() && dd.sem.Len() >= *flag_i_database_concurrent_write_semaphore-1 {
for {
select {
case <-time.Tick(33 * time.Millisecond):
counter := attempts.Add(1)
if counter < 17 { // 561 ms timeout ; went from 33 to 66 =D see the power of 369 with Q?
goto TRY_ACQUIRE
} else {
return errors.New("failed acquire lock within timeout")
}
}
}
}
}
return nil
}
func (dd *database_document) is_safe() {
if dd.sem == nil {
dd.sem = sema.New(*flag_i_database_concurrent_write_semaphore)
}
if dd.mu == nil {
dd.mu = &sync.RWMutex{}
}
if dd.locked == nil {
dd.locked = &atomic.Bool{}
}
}
func (dd *database_document) Unlock() {
dd.is_safe()
dd.locked.Store(false)
dd.sem.Release()
dd.mu.Unlock()
}