-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrefcount.go
More file actions
44 lines (38 loc) · 775 Bytes
/
refcount.go
File metadata and controls
44 lines (38 loc) · 775 Bytes
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
package gpio
import (
"sync/atomic"
"syscall"
)
// Atomic reference counting fd closer
// If Linux is okay with random chip/handle/event fd closing order,
// this mechanism is redundant and should be removed. TODO verify
type fdArc struct {
fd int
c int32
e chan error
}
func newFdArc(fd int) fdArc {
return fdArc{fd: fd, c: 1, e: make(chan error, 1)}
}
func (f *fdArc) incref() bool {
nc := atomic.AddInt32(&f.c, 1)
return nc > 1
}
func (f *fdArc) decref() {
nc := atomic.AddInt32(&f.c, -1)
if nc == 0 {
err := syscall.Close(f.fd)
select {
case f.e <- err:
default:
panic("code error err chan is busy")
}
} else if nc < 0 {
panic("code error excess fdArc.decref")
}
}
func (f *fdArc) wait() error {
err := <-f.e
close(f.e)
return err
}