github.com/ava-labs/avalanchego@v1.11.11/vms/rpcchainvm/runtime/manager.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package runtime
     5  
     6  import (
     7  	"context"
     8  	"sync"
     9  )
    10  
    11  // Manages tracking and shutdown of VM runtimes.
    12  type manager struct {
    13  	lock     sync.Mutex
    14  	runtimes []Stopper
    15  }
    16  
    17  // NewManager returns manager of VM runtimes.
    18  //
    19  // TODO: If a runtime exits before the call to `manager.Stop`, it would be nice
    20  // to remove it from the current set.
    21  func NewManager() Manager {
    22  	return &manager{}
    23  }
    24  
    25  func (m *manager) Stop(ctx context.Context) {
    26  	var wg sync.WaitGroup
    27  	m.lock.Lock()
    28  	defer func() {
    29  		m.lock.Unlock()
    30  		wg.Wait()
    31  	}()
    32  
    33  	wg.Add(len(m.runtimes))
    34  	for _, rt := range m.runtimes {
    35  		go func(runtime Stopper) {
    36  			defer wg.Done()
    37  			runtime.Stop(ctx)
    38  		}(rt)
    39  	}
    40  	m.runtimes = nil
    41  }
    42  
    43  func (m *manager) TrackRuntime(runtime Stopper) {
    44  	m.lock.Lock()
    45  	defer m.lock.Unlock()
    46  
    47  	m.runtimes = append(m.runtimes, runtime)
    48  }