Skip to content

Commit 3b3efdd

Browse files
committed
multi: Use atomic types in unexported modules.
1 parent 152aa8b commit 3b3efdd

File tree

8 files changed

+49
-54
lines changed

8 files changed

+49
-54
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
module github.com/decred/dcrd
22

3-
go 1.17
3+
go 1.19
44

55
require (
66
github.com/davecgh/go-spew v1.1.1

internal/blockchain/indexers/indexsubscriber.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) 2021-2022 The Decred developers
1+
// Copyright (c) 2021-2023 The Decred developers
22
// Use of this source code is governed by an ISC
33
// license that can be found in the LICENSE file.
44

@@ -122,7 +122,7 @@ func (s *IndexSubscription) stop() error {
122122

123123
// IndexSubscriber subscribes clients for index updates.
124124
type IndexSubscriber struct {
125-
subscribers uint32 // update atomically.
125+
subscribers atomic.Uint32
126126

127127
c chan IndexNtfn
128128
subscriptions map[string]*IndexSubscription
@@ -172,7 +172,7 @@ func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexS
172172
}
173173

174174
prereq.dependent = sub
175-
atomic.AddUint32(&s.subscribers, 1)
175+
s.subscribers.Add(1)
176176

177177
return sub, nil
178178
}
@@ -183,14 +183,14 @@ func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexS
183183
s.subscriptions[sub.id] = sub
184184
s.mtx.Unlock()
185185

186-
atomic.AddUint32(&s.subscribers, 1)
186+
s.subscribers.Add(1)
187187

188188
return sub, nil
189189
}
190190

191191
// Notify relays an index notification to subscribed indexes for processing.
192192
func (s *IndexSubscriber) Notify(ntfn *IndexNtfn) {
193-
subscribers := atomic.LoadUint32(&s.subscribers)
193+
subscribers := s.subscribers.Load()
194194

195195
// Only relay notifications when there are subscribed indexes
196196
// to be notified.

internal/mempool/mempool.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,7 @@ type orphanTx struct {
239239
// and relayed to other peers. It is safe for concurrent access from multiple
240240
// peers.
241241
type TxPool struct {
242-
// The following variables must only be used atomically.
243-
lastUpdated int64 // last time pool was updated.
242+
lastUpdated atomic.Int64 // last time pool was updated.
244243

245244
mtx sync.RWMutex
246245
cfg Config
@@ -821,7 +820,7 @@ func (mp *TxPool) removeTransaction(tx *dcrutil.Tx, removeRedeemers bool) {
821820

822821
delete(mp.pool, *txHash)
823822

824-
atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
823+
mp.lastUpdated.Store(time.Now().Unix())
825824

826825
// Inform associated fee estimator that the transaction has been removed
827826
// from the mempool
@@ -909,7 +908,7 @@ func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint, txDesc *TxD
909908
for _, txIn := range msgTx.TxIn {
910909
mp.outpoints[txIn.PreviousOutPoint] = txDesc
911910
}
912-
atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
911+
mp.lastUpdated.Store(time.Now().Unix())
913912

914913
// Add unconfirmed exists address index entries associated with the
915914
// transaction if enabled.
@@ -2283,7 +2282,7 @@ func (mp *TxPool) miningDescs() []*mining.TxDesc {
22832282
//
22842283
// This function is safe for concurrent access.
22852284
func (mp *TxPool) LastUpdated() time.Time {
2286-
return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0)
2285+
return time.Unix(mp.lastUpdated.Load(), 0)
22872286
}
22882287

22892288
// MiningView returns a slice of mining descriptors for all the transactions

internal/mining/cpuminer/cpuminer.go

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copyright (c) 2014-2016 The btcsuite developers
2-
// Copyright (c) 2015-2022 The Decred developers
2+
// Copyright (c) 2015-2023 The Decred developers
33
// Use of this source code is governed by an ISC
44
// license that can be found in the LICENSE file.
55

@@ -55,8 +55,8 @@ var (
5555
// speedStats houses tracking information used to monitor the hashing speed of
5656
// the CPU miner.
5757
type speedStats struct {
58-
totalHashes uint64 // atomic
59-
elapsedMicros uint64 // atomic
58+
totalHashes atomic.Uint64
59+
elapsedMicros atomic.Uint64
6060
}
6161

6262
// Config is a descriptor containing the CPU miner configuration.
@@ -112,7 +112,7 @@ type Config struct {
112112
// workers which means it will be idle. The number of worker goroutines for the
113113
// normal mining mode can be set via the SetNumWorkers method.
114114
type CPUMiner struct {
115-
numWorkers uint32 // update atomically
115+
numWorkers atomic.Uint32
116116

117117
sync.Mutex
118118
g *mining.BgBlkTmplGenerator
@@ -165,8 +165,8 @@ out:
165165
hashesPerSec = 0
166166
m.Lock()
167167
for _, stats := range m.speedStats {
168-
totalHashes := atomic.SwapUint64(&stats.totalHashes, 0)
169-
elapsedMicros := atomic.SwapUint64(&stats.elapsedMicros, 0)
168+
totalHashes := stats.totalHashes.Swap(0)
169+
elapsedMicros := stats.elapsedMicros.Swap(0)
170170
elapsedSecs := (elapsedMicros / 1000000)
171171
if totalHashes == 0 || elapsedSecs == 0 {
172172
continue
@@ -285,9 +285,9 @@ func (m *CPUMiner) solveBlock(ctx context.Context, header *wire.BlockHeader, sta
285285
hashesCompleted := uint64(0)
286286
start := time.Now()
287287
updateSpeedStats := func() {
288-
atomic.AddUint64(&stats.totalHashes, hashesCompleted)
288+
stats.totalHashes.Add(hashesCompleted)
289289
elapsedMicros := time.Since(start).Microseconds()
290-
atomic.AddUint64(&stats.elapsedMicros, uint64(elapsedMicros))
290+
stats.elapsedMicros.Add(uint64(elapsedMicros))
291291

292292
hashesCompleted = 0
293293
start = time.Now()
@@ -552,7 +552,7 @@ out:
552552
// Update the number of running workers.
553553
case <-m.updateNumWorkers:
554554
numRunning := uint32(len(runningWorkers))
555-
numWorkers := atomic.LoadUint32(&m.numWorkers)
555+
numWorkers := m.numWorkers.Load()
556556

557557
// No change.
558558
if numWorkers == numRunning {
@@ -678,7 +678,7 @@ func (m *CPUMiner) SetNumWorkers(numWorkers int32) {
678678
} else if targetNumWorkers > MaxNumWorkers {
679679
targetNumWorkers = MaxNumWorkers
680680
}
681-
atomic.StoreUint32(&m.numWorkers, targetNumWorkers)
681+
m.numWorkers.Store(targetNumWorkers)
682682

683683
// Set the normal mining state accordingly.
684684
if targetNumWorkers != 0 {
@@ -699,7 +699,7 @@ func (m *CPUMiner) SetNumWorkers(numWorkers int32) {
699699
//
700700
// This function is safe for concurrent access.
701701
func (m *CPUMiner) NumWorkers() int32 {
702-
return int32(atomic.LoadUint32(&m.numWorkers))
702+
return int32(m.numWorkers.Load())
703703
}
704704

705705
// GenerateNBlocks generates the requested number of blocks in the discrete
@@ -826,14 +826,15 @@ out:
826826
//
827827
// See the documentation for CPUMiner type for more details.
828828
func New(cfg *Config) *CPUMiner {
829-
return &CPUMiner{
829+
miner := &CPUMiner{
830830
g: cfg.BgBlkTmplGenerator,
831831
cfg: cfg,
832-
numWorkers: defaultNumWorkers,
833832
updateNumWorkers: make(chan struct{}),
834833
queryHashesPerSec: make(chan float64),
835834
speedStats: make(map[uint64]*speedStats),
836835
minedOnParents: make(map[chainhash.Hash]uint8),
837836
quit: make(chan struct{}),
838837
}
838+
miner.numWorkers.Store(defaultNumWorkers)
839+
return miner
839840
}

internal/mining/mining_harness_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) 2020-2022 The Decred developers
1+
// Copyright (c) 2020-2023 The Decred developers
22
// Use of this source code is governed by an ISC
33
// license that can be found in the LICENSE file.
44

@@ -263,7 +263,7 @@ type fakeTxSource struct {
263263
votes map[chainhash.Hash][]VoteDesc
264264
tspends map[chainhash.Hash]*dcrutil.Tx
265265
miningView *TxMiningView
266-
lastUpdated int64
266+
lastUpdated atomic.Int64
267267
}
268268

269269
// isTransactionInTxSource returns whether or not the passed transaction exists
@@ -289,7 +289,7 @@ func (p *fakeTxSource) isTransactionStaged(hash *chainhash.Hash) bool {
289289
// LastUpdated returns the last time a transaction was added to or removed from
290290
// the fake tx source.
291291
func (p *fakeTxSource) LastUpdated() time.Time {
292-
return time.Unix(atomic.LoadInt64(&p.lastUpdated), 0)
292+
return time.Unix(p.lastUpdated.Load(), 0)
293293
}
294294

295295
// HaveTransaction returns whether or not the passed transaction hash exists in
@@ -508,7 +508,7 @@ func (p *fakeTxSource) addTransaction(tx *dcrutil.Tx, txType stake.TxType, heigh
508508
for _, txIn := range msgTx.TxIn {
509509
p.outpoints[txIn.PreviousOutPoint] = tx
510510
}
511-
atomic.StoreInt64(&p.lastUpdated, time.Now().Unix())
511+
p.lastUpdated.Store(time.Now().Unix())
512512
}
513513

514514
// insertVote inserts a vote into the map of block votes.
@@ -607,7 +607,7 @@ func (p *fakeTxSource) RemoveTransaction(tx *dcrutil.Tx, removeRedeemers,
607607

608608
delete(p.pool, *txHash)
609609

610-
atomic.StoreInt64(&p.lastUpdated, time.Now().Unix())
610+
p.lastUpdated.Store(time.Now().Unix())
611611

612612
// Stop tracking if it's a tspend.
613613
delete(p.tspends, *txHash)

internal/rpcserver/rpcserver.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copyright (c) 2013-2016 The btcsuite developers
2-
// Copyright (c) 2015-2022 The Decred developers
2+
// Copyright (c) 2015-2023 The Decred developers
33
// Use of this source code is governed by an ISC
44
// license that can be found in the LICENSE file.
55

@@ -4913,8 +4913,7 @@ func handleVersion(_ context.Context, _ *Server, _ interface{}) (interface{}, er
49134913

49144914
// Server provides a concurrent safe RPC server to a chain server.
49154915
type Server struct {
4916-
// atomic
4917-
numClients int32
4916+
numClients atomic.Int32
49184917

49194918
cfg Config
49204919
hmac hash.Hash
@@ -5097,7 +5096,7 @@ func (s *Server) NotifyWinningTickets(wtnd *WinningTicketsNtfnData) {
50975096
//
50985097
// This function is safe for concurrent access.
50995098
func (s *Server) limitConnections(w http.ResponseWriter, remoteAddr string) bool {
5100-
if int(atomic.LoadInt32(&s.numClients)+1) > s.cfg.RPCMaxClients {
5099+
if int(s.numClients.Load()+1) > s.cfg.RPCMaxClients {
51015100
log.Infof("Max RPC clients exceeded [%d] - "+
51025101
"disconnecting client %s", s.cfg.RPCMaxClients,
51035102
remoteAddr)
@@ -5114,7 +5113,7 @@ func (s *Server) limitConnections(w http.ResponseWriter, remoteAddr string) bool
51145113
//
51155114
// This function is safe for concurrent access.
51165115
func (s *Server) incrementClients() {
5117-
atomic.AddInt32(&s.numClients, 1)
5116+
s.numClients.Add(1)
51185117
}
51195118

51205119
// decrementClients subtracts one from the number of connected RPC clients.
@@ -5123,7 +5122,7 @@ func (s *Server) incrementClients() {
51235122
//
51245123
// This function is safe for concurrent access.
51255124
func (s *Server) decrementClients() {
5126-
atomic.AddInt32(&s.numClients, -1)
5125+
s.numClients.Add(-1)
51275126
}
51285127

51295128
// authMAC calculates the MAC (currently HMAC-SHA256) of an Authorization

internal/rpcserver/rpcwebsocket.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copyright (c) 2013-2016 The btcsuite developers
2-
// Copyright (c) 2015-2022 The Decred developers
2+
// Copyright (c) 2015-2023 The Decred developers
33
// Use of this source code is governed by an ISC
44
// license that can be found in the LICENSE file.
55

@@ -1262,8 +1262,7 @@ type wsResponse struct {
12621262
// subsystems can't block. Ultimately, all messages are sent via the
12631263
// outHandler.
12641264
type wsClient struct {
1265-
// The following variables must only be used atomically.
1266-
disconnected int32 // Websocket client disconnected?
1265+
disconnected atomic.Bool // Websocket client disconnected?
12671266

12681267
sync.Mutex
12691268

@@ -1309,7 +1308,7 @@ type wsClient struct {
13091308
func (c *wsClient) shouldLogReadError(err error) bool {
13101309
// No logging when the client is being forcibly disconnected from the server
13111310
// side.
1312-
if atomic.LoadInt32(&c.disconnected) != 0 {
1311+
if c.disconnected.Load() {
13131312
return false
13141313
}
13151314

@@ -1327,7 +1326,7 @@ func (c *wsClient) shouldLogReadError(err error) bool {
13271326
// must be run as a goroutine.
13281327
func (c *wsClient) inHandler(ctx context.Context) {
13291328
out:
1330-
for atomic.LoadInt32(&c.disconnected) == 0 {
1329+
for !c.disconnected.Load() {
13311330
_, msg, err := c.conn.ReadMessage()
13321331
if err != nil {
13331332
// Log the error if it's not due to disconnecting.
@@ -1916,13 +1915,13 @@ func (c *wsClient) QueueNotification(marshalledJSON []byte) error {
19161915

19171916
// Disconnected returns whether or not the websocket client is disconnected.
19181917
func (c *wsClient) Disconnected() bool {
1919-
return atomic.LoadInt32(&c.disconnected) > 0
1918+
return c.disconnected.Load()
19201919
}
19211920

19221921
// Disconnect disconnects the websocket client.
19231922
func (c *wsClient) Disconnect() {
19241923
// Nothing to do if already disconnected.
1925-
if atomic.AddInt32(&c.disconnected, 1) != 1 {
1924+
if !c.disconnected.CompareAndSwap(false, true) {
19261925
return
19271926
}
19281927

server.go

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copyright (c) 2013-2016 The btcsuite developers
2-
// Copyright (c) 2015-2022 The Decred developers
2+
// Copyright (c) 2015-2023 The Decred developers
33
// Use of this source code is governed by an ISC
44
// license that can be found in the LICENSE file.
55

@@ -466,11 +466,9 @@ func (ps *peerState) ResolveLocalAddress(netType addrmgr.NetAddressType, addrMgr
466466
// server provides a Decred server for handling communications to and from
467467
// Decred peers.
468468
type server struct {
469-
// The following variables must only be used atomically.
470-
// Putting the uint64s first makes them 64-bit aligned for 32-bit systems.
471-
bytesReceived uint64 // Total bytes received from all peers since start.
472-
bytesSent uint64 // Total bytes sent by all peers since start.
473-
shutdown int32
469+
bytesReceived atomic.Uint64 // Total bytes received from all peers since start.
470+
bytesSent atomic.Uint64 // Total bytes sent by all peers since start.
471+
shutdown atomic.Bool
474472

475473
// minKnownWork houses the minimum known work from the associated network
476474
// params converted to a uint256 so the conversion only needs to be
@@ -1693,7 +1691,7 @@ func (s *server) handleAddPeerMsg(state *peerState, sp *serverPeer) bool {
16931691
}
16941692

16951693
// Ignore new peers if we're shutting down.
1696-
if atomic.LoadInt32(&s.shutdown) != 0 {
1694+
if s.shutdown.Load() {
16971695
srvrLog.Infof("New peer %s ignored - server is shutting down", sp)
16981696
sp.Disconnect()
16991697
return false
@@ -2472,20 +2470,19 @@ func (s *server) AddedNodeInfo() []*serverPeer {
24722470
// AddBytesSent adds the passed number of bytes to the total bytes sent counter
24732471
// for the server. It is safe for concurrent access.
24742472
func (s *server) AddBytesSent(bytesSent uint64) {
2475-
atomic.AddUint64(&s.bytesSent, bytesSent)
2473+
s.bytesSent.Add(bytesSent)
24762474
}
24772475

24782476
// AddBytesReceived adds the passed number of bytes to the total bytes received
24792477
// counter for the server. It is safe for concurrent access.
24802478
func (s *server) AddBytesReceived(bytesReceived uint64) {
2481-
atomic.AddUint64(&s.bytesReceived, bytesReceived)
2479+
s.bytesReceived.Add(bytesReceived)
24822480
}
24832481

24842482
// NetTotals returns the sum of all bytes received and sent across the network
24852483
// for all peers. It is safe for concurrent access.
24862484
func (s *server) NetTotals() (uint64, uint64) {
2487-
return atomic.LoadUint64(&s.bytesReceived),
2488-
atomic.LoadUint64(&s.bytesSent)
2485+
return s.bytesReceived.Load(), s.bytesSent.Load()
24892486
}
24902487

24912488
// notifiedWinningTickets returns whether or not the winning tickets
@@ -3111,7 +3108,7 @@ func (s *server) Run(ctx context.Context) {
31113108

31123109
// Wait until the server is signalled to shutdown.
31133110
<-ctx.Done()
3114-
atomic.AddInt32(&s.shutdown, 1)
3111+
s.shutdown.Store(true)
31153112

31163113
srvrLog.Warnf("Server shutting down")
31173114

0 commit comments

Comments
 (0)