chenshijun
2020-06-04 47a19e070f57d92aadf52c62361da6ab5397bd4c
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package shmqueue
 
import (
    "context"
    "fmt"
    shm "basic.com/valib/goshm.git"
    "reflect"
    "runtime"
    "sync/atomic"
    "time"
    "unsafe"
)
 
const (
    TimePeriodPutOrGet = time.Duration(5)*time.Millisecond //ms
)
 
//Element info
type ElemInfo struct {
    PicId  int
    InfoId int
}
 
//queue info
type esCache struct {
    putNo uint32
    getNo uint32
    value ElemInfo
}
 
// lock free queue struct
type esQueue struct {
    capacity uint32
    capMod   uint32
    putPos   uint32
    getPos   uint32
    cache    []esCache
}
 
type EsQueueInfo struct {
    EsCaches []esCache
    ShmKey   int
    ShmID    int
    ShmData  []byte
    Queue    *esQueue
}
 
// ptr2esCache convert unsafe.Pointer to []esCache
func ptr2esCache(s unsafe.Pointer, size int) []esCache {
    var x reflect.SliceHeader
    x.Len = size
    x.Cap = size
    x.Data = uintptr(s)
    return *(*[]esCache)(unsafe.Pointer(&x))
}
 
// bytes2shmEsQueue convert []byte to *esQueue
func bytes2shmEsQueue(b []byte) *esQueue {
    return (*esQueue)(unsafe.Pointer(
        (*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
    ))
}
 
// NewQueue new and attach a shm queue if no exist, otherwise return exist
func NewQueue(ctx context.Context, key int, cap int) *EsQueueInfo {
    var shmLen uint32
    var datainfo esCache
    var shmstruct esQueue
    var eqi EsQueueInfo
 
    shmblocks := minQuantity(uint32(cap))
    shmLen = shmblocks*uint32(unsafe.Sizeof(datainfo)) + uint32(unsafe.Sizeof(shmstruct))
 
    data, shmid := CreateRawShm(ctx, int(shmLen), key)
    q := bytes2shmEsQueue(data)
    //init parameters
    q.capacity = shmblocks
    q.capMod = q.capacity - 1
    q.putPos = 0
    q.getPos = 0
 
    eqi.EsCaches = ptr2esCache(unsafe.Pointer(&q.cache), int(q.capacity))
 
    for i := 0; i < int(q.capacity); i++ {
        eqi.EsCaches[i].getNo = uint32(i)
        eqi.EsCaches[i].putNo = uint32(i)
    }
    cache := &eqi.EsCaches[0]
    cache.getNo = q.capacity
    cache.putNo = q.capacity
 
    //fmt.Println("NewQueue EsCaches:", eqi.EsCaches)
 
    eqi.ShmData = data
    eqi.ShmID = shmid
    eqi.ShmKey = key
    eqi.Queue = q
 
    return &eqi
}
 
// AttachQueue attach an exist shm queue
func AttachQueue(ctx context.Context, key int) *EsQueueInfo {
 
    var eqi EsQueueInfo
    data, shmid := AttachRawShm(ctx, key)
    shmdata := bytes2shmEsQueue(data)
    eqi.EsCaches = ptr2esCache(unsafe.Pointer(&shmdata.cache), int(shmdata.capacity))
    //fmt.Println("AttachQueue EsCaches:", eqi.EsCaches)
 
    eqi.Queue = shmdata
    eqi.ShmKey = key
    eqi.ShmID = shmid
    eqi.ShmData = data
 
    return &eqi
}
 
// ReleaseQueue detach an exist shm queue
func (eqi *EsQueueInfo) ReleaseQueue() {
    fmt.Printf("ReleaseQueue: key=%x\n", eqi.ShmKey)
    DetachShm(eqi.ShmData)
}
 
// RemoveShmId remove an exist shm queue (ipcrm -m shmid)
func (eqi *EsQueueInfo) RemoveShmId() error {
    fmt.Printf("RemoveShmId: key=%x\n", eqi.ShmKey)
    return shm.Rm(eqi.ShmID)
}
 
// Status status of shm queue
func (eqi *EsQueueInfo) Status() string {
    q := eqi.Queue
    getPos := atomic.LoadUint32(&q.getPos)
    putPos := atomic.LoadUint32(&q.putPos)
    return fmt.Sprintf("Queue{Capacity: %v, putPos: %v, getPos: %v, size:%v, cache: %v}",
        eqi.QueueCapacity(), putPos, getPos, eqi.QueueSize(), eqi.EsCaches)
}
 
// Capacity queue 容量,总大小
func (eqi *EsQueueInfo) QueueCapacity() int {
    return int(eqi.Queue.capMod)
}
 
// Size queue 实际大小
func (eqi *EsQueueInfo) QueueSize() int {
    var putPos, getPos uint32
    var quantity uint32
 
    getPos = atomic.LoadUint32(&eqi.Queue.getPos)
    putPos = atomic.LoadUint32(&eqi.Queue.putPos)
 
    if putPos >= getPos {
        quantity = putPos - getPos
    } else {
        quantity = eqi.Queue.capMod + (putPos - getPos)
    }
 
    return int(quantity)
}
 
// Status status of shm queue
func (eqi *EsQueueInfo) QueueElements() []ElemInfo {
    var elems []ElemInfo
 
    for i := 0; i < len(eqi.EsCaches); i++ {
        if eqi.EsCaches[i].value.PicId != -1 && eqi.EsCaches[i].value.InfoId != -1 &&
            eqi.EsCaches[i].value.PicId != 0 && eqi.EsCaches[i].value.InfoId != 0 {
            elems = append(elems, eqi.EsCaches[i].value)
        }
    }
 
    return elems
}
 
// Put 单次写入,可能失败
func (eqi *EsQueueInfo) Put(val ElemInfo) (bool, int) {
    var putPos, putPosNew, getPos, posCnt uint32
    var cache *esCache
    capMod := eqi.Queue.capMod
 
    getPos = atomic.LoadUint32(&eqi.Queue.getPos)
    putPos = atomic.LoadUint32(&eqi.Queue.putPos)
 
    if putPos >= getPos {
        posCnt = putPos - getPos
    } else {
        posCnt = capMod + (putPos - getPos)
    }
 
    //todo
    //if posCnt >= capMod-1 {
    if posCnt >= capMod {
        runtime.Gosched()
        return false, int(posCnt)
    }
 
    putPosNew = putPos + 1
    if !atomic.CompareAndSwapUint32(&eqi.Queue.putPos, putPos, putPosNew) {
        fmt.Println("CompareAndSwapUint32 error")
        runtime.Gosched()
        return false, int(posCnt)
    }
 
    cache = &(eqi.EsCaches[putPosNew&capMod])
 
    for {
        getNo := atomic.LoadUint32(&cache.getNo)
        putNo := atomic.LoadUint32(&cache.putNo)
        if putPosNew == putNo && getNo == putNo {
            cache.value = val
            atomic.AddUint32(&cache.putNo, eqi.Queue.capacity)
            return true, int(posCnt + 1)
        } else {
            runtime.Gosched()
        }
    }
}
 
//PutForce 强制写入,失败则继续重写,直到成功为止
func (eqi *EsQueueInfo) PutForce(ctx context.Context, val ElemInfo) int {
    ok, qua := eqi.Put(val)
    for !ok {
    loopB:
        for {
            select {
            case <-ctx.Done():
                return 0
            default:
                ok, qua = eqi.Put(val)
                if ok {
                    break loopB
                }
                time.Sleep(TimePeriodPutOrGet)
            }
        }
    }
 
    return qua
}
 
//PutForceWithinTime 在timeout ms的时间内,强制写入,失败则继续重写,直到成功为止或者超时退出
func (eqi *EsQueueInfo) PutForceWithinTime(ctx context.Context, val ElemInfo, timeout int) (bool, int) {
    ok, qua := eqi.Put(val)
    if ok {
        return ok, qua
    }
 
    to := time.NewTimer(time.Duration(timeout) * time.Millisecond)
    defer to.Stop()
 
    loopB:
        for {
            select {
            case <-ctx.Done():
                return false, 0
            case <-to.C:
                return false, 0
            default:
                ok, qua = eqi.Put(val)
                if ok {
                    break loopB
                }
                time.Sleep(TimePeriodPutOrGet)
            }
        }
    return ok, qua
}
 
// Get 单次获取,可能失败
func (eqi *EsQueueInfo) Get() (ElemInfo, bool, int) {
    var putPos, getPos, getPosNew, posCnt uint32
    var cache *esCache
    capMod := eqi.Queue.capMod
 
    putPos = atomic.LoadUint32(&eqi.Queue.putPos)
    getPos = atomic.LoadUint32(&eqi.Queue.getPos)
 
    if putPos >= getPos {
        posCnt = putPos - getPos
    } else {
        posCnt = capMod + (putPos - getPos)
    }
 
    if posCnt < 1 {
        runtime.Gosched()
        return ElemInfo{}, false, int(posCnt)
    }
 
    getPosNew = getPos + 1
    if !atomic.CompareAndSwapUint32(&eqi.Queue.getPos, getPos, getPosNew) {
        runtime.Gosched()
        return ElemInfo{}, false, int(posCnt)
    }
 
    cache = &(eqi.EsCaches[getPosNew&capMod])
 
    for {
        getNo := atomic.LoadUint32(&cache.getNo)
        putNo := atomic.LoadUint32(&cache.putNo)
        if getPosNew == getNo && getNo == putNo-eqi.Queue.capacity {
            val := cache.value
            cache.value = ElemInfo{PicId: 0, InfoId:0}
            atomic.AddUint32(&cache.getNo, eqi.Queue.capacity)
            return val, true, int(posCnt - 1)
        } else {
            runtime.Gosched()
        }
    }
}
 
//GetForce 强制获取数据,失败则继续获取,直到成功为止
func (eqi *EsQueueInfo) GetForce(ctx context.Context) (ElemInfo, int) {
    val, ok, qua := eqi.Get()
    for !ok {
    loopB:
        for {
            select {
            case <-ctx.Done():
                return ElemInfo{}, 0
            default:
                val, ok, qua = eqi.Get()
                if ok {
                    break loopB
                }
                time.Sleep(TimePeriodPutOrGet)
            }
        }
    }
 
    return val, qua
}
 
//GetForceWithinTime 在timeout ms的时间内,强制获取数据,失败则继续获取,直到成功为止
func (eqi *EsQueueInfo) GetForceWithinTime(ctx context.Context, timeout int) (ElemInfo, bool, int) {
    val, ok, qua := eqi.Get()
    if ok {
        return val, ok, qua
    }
 
    to := time.NewTimer(time.Duration(timeout) * time.Millisecond)
    defer to.Stop()
 
    loopB:
        for {
            select {
            case <-ctx.Done():
                return ElemInfo{}, false, 0
            case <-to.C:
                return ElemInfo{}, false, 0
            default:
                val, ok, qua = eqi.Get()
                if ok {
                    break loopB
                }
                time.Sleep(TimePeriodPutOrGet)
            }
        }
    return val, ok, qua
}
 
// round 到最近的2的倍数
func minQuantity(v uint32) uint32 {
    if v < 2 {
        return 2
    }
    v--
    v |= v >> 1
    v |= v >> 2
    v |= v >> 4
    v |= v >> 8
    v |= v >> 16
    v++
    return v
}