Skip to content

Commit d0eb273

Browse files
committed
store conn state as atomic
1 parent dabcc95 commit d0eb273

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

internal/conn/conn.go

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ type conn struct {
5656
done chan struct{}
5757
endpoint endpoint.Endpoint // ro access
5858
closed bool
59-
state State
59+
state uint32
6060
lastUsage time.Time
6161
onClose []func(*conn)
6262
onTransportErrors []func(ctx context.Context, cc Conn, cause error)
@@ -80,11 +80,9 @@ func (c *conn) LastUsage() time.Time {
8080
}
8181

8282
func (c *conn) IsState(states ...State) bool {
83-
c.mtx.RLock()
84-
defer c.mtx.RUnlock()
85-
83+
state := State(atomic.LoadUint32(&c.state))
8684
for _, s := range states {
87-
if s == c.state {
85+
if s == state {
8886
return true
8987
}
9088
}
@@ -144,13 +142,15 @@ func (c *conn) SetState(s State) State {
144142
}
145143

146144
func (c *conn) setState(s State) State {
147-
trace.DriverOnConnStateChange(
148-
c.config.Trace(),
149-
c.endpoint.Copy(),
150-
c.state,
151-
)(s)
152-
c.state = s
153-
return c.state
145+
state := atomic.LoadUint32(&c.state)
146+
if atomic.CompareAndSwapUint32(&c.state, state, uint32(s)) {
147+
trace.DriverOnConnStateChange(
148+
c.config.Trace(),
149+
c.endpoint.Copy(),
150+
State(state),
151+
)(s)
152+
}
153+
return s
154154
}
155155

156156
func (c *conn) Unban() State {
@@ -169,9 +169,7 @@ func (c *conn) Unban() State {
169169
}
170170

171171
func (c *conn) GetState() (s State) {
172-
c.mtx.RLock()
173-
defer c.mtx.RUnlock()
174-
return c.state
172+
return State(atomic.LoadUint32(&c.state))
175173
}
176174

177175
func (c *conn) take(ctx context.Context) (cc *grpc.ClientConn, err error) {
@@ -475,7 +473,7 @@ func newConn(e endpoint.Endpoint, config Config, opts ...option) *conn {
475473
)
476474
c := &conn{
477475
grpcDialOptions: grpcDialOptions,
478-
state: Created,
476+
state: uint32(Created),
479477
endpoint: e,
480478
config: config,
481479
done: make(chan struct{}),

0 commit comments

Comments
 (0)