-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathlockfree.go
85 lines (77 loc) · 2.11 KB
/
lockfree.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
/*
* Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
*/
package lockfree
import (
"fmt"
"sync/atomic"
)
// Lockfree 包装类,内部包装了生产者和消费者
type Lockfree[T any] struct {
writer *Producer[T]
consumer *consumer[T]
status int32
}
// NewLockfree 自定义创建消费端的Disruptor
// capacity:buffer的容量大小,类似于chan的大小,但要求必须是2^n,即2的指数倍,如果不是的话会被修改
// handler:消费端的事件处理器
// blocks:读取阻塞时的处理策略
func NewLockfree[T any](capacity int, handler EventHandler[T], blocks blockStrategy) *Lockfree[T] {
// 重新计算正确的容量
capacity = minSuitableCap(capacity)
seqer := newSequencer(capacity)
rbuf := newRingBuffer[T](capacity)
cmer := newConsumer[T](rbuf, handler, seqer, blocks)
writer := newProducer[T](seqer, rbuf, blocks)
return &Lockfree[T]{
writer: writer,
consumer: cmer,
status: READY,
}
}
func (d *Lockfree[T]) Start() error {
if atomic.CompareAndSwapInt32(&d.status, READY, RUNNING) {
// 启动消费者
if err := d.consumer.start(); err != nil {
// 恢复现场
atomic.CompareAndSwapInt32(&d.status, RUNNING, READY)
return err
}
// 启动生产者
if err := d.writer.start(); err != nil {
// 恢复现场
atomic.CompareAndSwapInt32(&d.status, RUNNING, READY)
return err
}
return nil
}
return fmt.Errorf(StartErrorFormat, "Disruptor")
}
func (d *Lockfree[T]) Producer() *Producer[T] {
return d.writer
}
func (d *Lockfree[T]) Running() bool {
return d.status == RUNNING
}
func (d *Lockfree[T]) Close() error {
if atomic.CompareAndSwapInt32(&d.status, RUNNING, READY) {
// 关闭生产者
if err := d.writer.close(); err != nil {
// 恢复现场
atomic.CompareAndSwapInt32(&d.status, READY, RUNNING)
return err
}
// 关闭消费者
if err := d.consumer.close(); err != nil {
// 恢复现场
atomic.CompareAndSwapInt32(&d.status, READY, RUNNING)
return err
}
// 关闭成功
return nil
}
return fmt.Errorf(CloseErrorFormat, "Disruptor")
}