Files
engine/common/ring_lock.go
langhuihui f4fb7881f7 增加Stream NeverTimeout属性,用于纯数据轨道的流保持不关闭
消除一处魔法数字
将TCP监听增加TLS支持
2023-06-04 11:02:45 +08:00

78 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package common
import (
"sync"
"sync/atomic"
)
type LockFrame[T any] struct {
DataFrame[T]
sync.RWMutex
}
type LockRing[T any] struct {
RingBuffer[LockFrame[T]]
Reset func(*DataFrame[T]) `json:"-" yaml:"-"`
Flag *int32
}
func (lr *LockRing[T]) Init(n int) *LockRing[T] {
var flag int32
if lr == nil {
lr = &LockRing[T]{}
}
lr.Reset = func(*DataFrame[T]) {
}
lr.RingBuffer.Init(n)
lr.Flag = &flag
lr.RingBuffer.Value.Lock()
return lr
}
func (rb *LockRing[T]) Read() *DataFrame[T] {
current := &rb.RingBuffer.Value
current.RLock()
defer current.RUnlock()
return &current.DataFrame
}
// func (rb *LockRing[T]) Step() {
// if atomic.CompareAndSwapInt32(rb.Flag, 0, 1) {
// current := rb.RingBuffer.MoveNext()
// current.Lock()
// rb.RingBuffer.LastValue.Unlock()
// //Flag不为1代表被Dispose了但尚未处理Done
// if !atomic.CompareAndSwapInt32(rb.Flag, 1, 0) {
// current.Unlock()
// }
// }
// }
func (rb *LockRing[T]) Write(value T) {
rb.Value.Value = value
if atomic.CompareAndSwapInt32(rb.Flag, 0, 1) {
current := rb.RingBuffer.MoveNext()
current.Lock()
if current.Sequence != 0 {
rb.Reset(&current.DataFrame)
}
current.Sequence = rb.RingBuffer.MoveCount
rb.LastValue.Unlock()
//Flag不为1代表被Dispose了但尚未处理Done
if !atomic.CompareAndSwapInt32(rb.Flag, 1, 0) {
current.Unlock()
}
}
}
func (rb *LockRing[T]) Dispose() {
current := &rb.RingBuffer.Value
if atomic.CompareAndSwapInt32(rb.Flag, 0, 2) {
current.Unlock()
} else if atomic.CompareAndSwapInt32(rb.Flag, 1, 2) {
//当前是1代表正在写入此时变成2但是Done的任务得交给NextW来处理
} else if atomic.CompareAndSwapInt32(rb.Flag, 0, 2) {
current.Unlock()
}
}