Skip to content

Commit cb712e6

Browse files
committed
explicit Start method for basic host
1 parent 6fb54b0 commit cb712e6

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

config/config.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ func (cfg *Config) NewNode(ctx context.Context) (host.Host, error) {
228228
}
229229
}
230230

231+
// start the host background tasks
232+
h.Start()
233+
231234
if router != nil {
232235
return routed.Wrap(h, router), nil
233236
}

p2p/host/basic/basic_host.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ type BasicHost struct {
7272

7373
proc goprocess.Process
7474

75-
bgcancel func()
75+
ctx context.Context
76+
cancel func()
7677
mx sync.Mutex
7778
lastAddrs []ma.Multiaddr
7879
}
@@ -171,8 +172,8 @@ func NewHost(ctx context.Context, net inet.Network, opts *HostOpts) (*BasicHost,
171172
net.SetStreamHandler(h.newStreamHandler)
172173

173174
bgctx, cancel := context.WithCancel(ctx)
174-
h.bgcancel = cancel
175-
go h.background(bgctx)
175+
h.ctx = bgctx
176+
h.cancel = cancel
176177

177178
return h, nil
178179
}
@@ -214,6 +215,11 @@ func New(net inet.Network, opts ...interface{}) *BasicHost {
214215
return h
215216
}
216217

218+
// Start starts background tasks in the host
219+
func (h *BasicHost) Start() {
220+
go h.background()
221+
}
222+
217223
// newConnHandler is the remote-opened conn handler for inet.Network
218224
func (h *BasicHost) newConnHandler(c inet.Conn) {
219225
// Clear protocols on connecting to new peer to avoid issues caused
@@ -288,10 +294,7 @@ func (h *BasicHost) PushIdentify() {
288294
}
289295
}
290296

291-
func (h *BasicHost) background(ctx context.Context) {
292-
// wait a bit for the host to initialize (avoid race with libp2p constructor)
293-
time.Sleep(1 * time.Second)
294-
297+
func (h *BasicHost) background() {
295298
// periodically schedules an IdentifyPush to update our peers for changes
296299
// in our address set (if needed)
297300
ticker := time.NewTicker(1 * time.Minute)
@@ -309,7 +312,7 @@ func (h *BasicHost) background(ctx context.Context) {
309312
case <-ticker.C:
310313
h.PushIdentify()
311314

312-
case <-ctx.Done():
315+
case <-h.ctx.Done():
313316
return
314317
}
315318
}
@@ -719,7 +722,7 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr {
719722

720723
// Close shuts down the Host's services (network, etc).
721724
func (h *BasicHost) Close() error {
722-
h.bgcancel()
725+
h.cancel()
723726
return h.proc.Close()
724727
}
725728

0 commit comments

Comments
 (0)