Skip to content

Commit

Permalink
use sync.Pool
Browse files Browse the repository at this point in the history
  • Loading branch information
beer-1 committed Sep 26, 2024
1 parent b3dd211 commit fc85735
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 22 deletions.
17 changes: 7 additions & 10 deletions x/move/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ type Keeper struct {
config moveconfig.MoveConfig

// TODO - remove after loader v2
moveVMs *[]types.VMEngine
moveVMMutx *sync.Mutex
moveVMSemaphore *semaphore.Weighted
vmPool *sync.Pool
vmPoolSema *semaphore.Weighted

feeCollector string
authority string
Expand Down Expand Up @@ -90,9 +89,8 @@ func NewKeeper(
moveConfig.ContractSimulationGasLimit = moveconfig.DefaultContractSimulationGasLimit
}

vmCount := 10
vms := make([]types.VMEngine, vmCount)
for i := 0; i < vmCount; i++ {
vmPool := new(sync.Pool)
vmPool.New = func() interface{} {
moveVM, err := vm.NewVM(vmtypes.InitiaVMConfig{
// TODO: check this before mainnet
AllowUnstable: true,
Expand All @@ -101,7 +99,7 @@ func NewKeeper(
panic(err)
}

vms[i] = &moveVM
return &moveVM
}

sb := collections.NewSchemaBuilder(storeService)
Expand All @@ -114,9 +112,8 @@ func NewKeeper(
msgRouter: msgRouter,
grpcRouter: grpcRouter,
config: moveConfig,
moveVMs: &vms,
moveVMMutx: new(sync.Mutex),
moveVMSemaphore: semaphore.NewWeighted(int64(vmCount)),
vmPool: vmPool,
vmPoolSema: semaphore.NewWeighted(int64(10)),
distrKeeper: distrKeeper,
StakingKeeper: stakingKeeper,
RewardKeeper: rewardKeeper,
Expand Down
17 changes: 5 additions & 12 deletions x/move/keeper/vmpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,16 @@ import (
"github.com/initia-labs/initia/x/move/types"
)

func (k Keeper) acquireVM(ctx context.Context) (vm types.VMEngine) {
err := k.moveVMSemaphore.Acquire(ctx, 1)
func (k Keeper) acquireVM(ctx context.Context) types.VMEngine {
err := k.vmPoolSema.Acquire(ctx, 1)
if err != nil {
panic(err)
}

k.moveVMMutx.Lock()
vm, *k.moveVMs = (*k.moveVMs)[0], (*k.moveVMs)[1:]
k.moveVMMutx.Unlock()

return
return k.vmPool.Get().(types.VMEngine)
}

func (k Keeper) releaseVM(vm types.VMEngine) {
k.moveVMMutx.Lock()
*k.moveVMs = append(*k.moveVMs, vm)
k.moveVMMutx.Unlock()

k.moveVMSemaphore.Release(1)
k.vmPool.Put(vm)
k.vmPoolSema.Release(1)
}

0 comments on commit fc85735

Please sign in to comment.