Skip to content

Commit

Permalink
rpc: use atomic value to avoid currently read/write
Browse files Browse the repository at this point in the history
  • Loading branch information
unclezoro committed Jun 3, 2019
1 parent 62ae3e1 commit eafffc6
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions client/rpc/ws_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"net"
"net/http"
"sync/atomic"

"fmt"
"strings"
Expand Down Expand Up @@ -492,7 +493,7 @@ type WSClient struct {
wg sync.WaitGroup

mtx sync.RWMutex
dialing bool
dialing atomic.Value

// Maximum reconnect attempts (0 or greater; default: 25).
// Less than 0 means always try to reconnect.
Expand Down Expand Up @@ -532,8 +533,8 @@ func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSCli
writeWait: defaultWriteWait,
pingPeriod: defaultPingPeriod,
protocol: protocol,
dialing: true,
}
c.dialing.Store(true)
c.BaseService = *cmn.NewBaseService(nil, "WSClient", c)
for _, option := range options {
option(c)
Expand Down Expand Up @@ -572,7 +573,7 @@ func (c *WSClient) OnStart() error {
c.wg.Add(1)
go c.dialRoutine()
} else {
c.dialing = false
c.dialing.Store(false)
}

c.startReadWriteRoutines()
Expand All @@ -596,7 +597,7 @@ func (c *WSClient) Stop() error {

// IsDialing returns true if the client is dialing right now.
func (c *WSClient) IsDialing() bool {
return c.dialing
return c.dialing.Load().(bool)
}

// IsActive returns true if the client is running and not dialing.
Expand Down Expand Up @@ -681,9 +682,9 @@ func (c *WSClient) dial() error {
func (c *WSClient) reconnect() error {
attempt := 0

c.dialing = true
c.dialing.Store(true)
defer func() {
c.dialing = false
c.dialing.Store(false)
}()
backOffDuration := 1 * time.Second
for {
Expand Down Expand Up @@ -722,9 +723,9 @@ func (c *WSClient) startReadWriteRoutines() {
func (c *WSClient) dialRoutine() {
dialTicker := time.NewTicker(defaultDialPeriod)
defer dialTicker.Stop()
c.dialing = true
c.dialing.Store(true)
defer func() {
c.dialing = false
c.dialing.Store(false)
c.wg.Done()
}()
for {
Expand Down

0 comments on commit eafffc6

Please sign in to comment.