-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathglobal_data.go
129 lines (106 loc) · 2.31 KB
/
global_data.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package gp
/*
#include <Python.h>
*/
import "C"
import (
"reflect"
"sync"
"sync/atomic"
"unsafe"
)
// ----------------------------------------------------------------------------
type holderList struct {
head *objectHolder
}
func (l *holderList) PushFront(holder *objectHolder) {
if l.head != nil {
l.head.prev = holder
holder.next = l.head
}
l.head = holder
}
func (l *holderList) Remove(holder *objectHolder) {
if holder.prev != nil {
holder.prev.next = holder.next
} else {
l.head = holder.next
}
if holder.next != nil {
holder.next.prev = holder.prev
}
}
// ----------------------------------------------------------------------------
const maxPyObjects = 128
type decRefList struct {
objects []*C.PyObject
mu sync.Mutex
}
func (l *decRefList) add(obj *C.PyObject) {
l.mu.Lock()
l.objects = append(l.objects, obj)
l.mu.Unlock()
}
func (l *decRefList) len() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.objects)
}
func (l *decRefList) decRefAll() {
l.mu.Lock()
list := l.objects
l.objects = make([]*C.PyObject, 0, maxPyObjects*2)
l.mu.Unlock()
for _, obj := range list {
C.Py_DecRef(obj)
}
}
// ----------------------------------------------------------------------------
type globalData struct {
typeMetas map[*C.PyObject]*typeMeta
pyTypes map[reflect.Type]*C.PyObject
holders holderList
decRefList decRefList
finished int32
alwaysDecRef bool
}
var (
global *globalData
)
func getGlobalData() *globalData {
return global
}
func (gd *globalData) addDecRef(obj *C.PyObject) {
if atomic.LoadInt32(&gd.finished) != 0 {
return
}
gd.decRefList.add(obj)
}
func (gd *globalData) decRefObjectsIfNeeded() {
if gd.alwaysDecRef || gd.decRefList.len() >= maxPyObjects {
gd.decRefList.decRefAll()
}
}
// ----------------------------------------------------------------------------
func initGlobal() {
global = &globalData{
typeMetas: make(map[*C.PyObject]*typeMeta),
pyTypes: make(map[reflect.Type]*C.PyObject),
}
}
func markFinished() {
atomic.StoreInt32(&global.finished, 1)
}
func cleanupGlobal() {
for _, meta := range global.typeMetas {
for _, method := range meta.methods {
def := method.def
if def != nil {
C.free(unsafe.Pointer(def.ml_name))
C.free(unsafe.Pointer(def.ml_doc))
C.free(unsafe.Pointer(def))
}
}
}
global = nil
}