github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/statemachine/db_state_machine.go (about) 1 // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package statemachine 16 17 import ( 18 "sync" 19 "sync/atomic" 20 "time" 21 22 "github.com/zuoyebang/bitalosdb/internal/consts" 23 ) 24 25 type DbStateMachine struct { 26 TaskLock sync.Mutex // compact-bithash|checkpoint 27 BitowerHighPriority [consts.DefaultBitowerNum]atomic.Bool 28 BitowerWrite [consts.DefaultBitowerNum]sync.Mutex // mem-flush|bitpage-flush/split |compact-bitable|checkpoint 29 30 bitpage struct { 31 flushCount atomic.Uint64 32 splitCount atomic.Uint64 33 } 34 } 35 36 func NewDbStateMachine() *DbStateMachine { 37 return &DbStateMachine{} 38 } 39 40 func (s *DbStateMachine) LockDbWrite() { 41 for i := range s.BitowerWrite { 42 s.BitowerWrite[i].Lock() 43 } 44 } 45 46 func (s *DbStateMachine) UnlockDbWrite() { 47 for i := range s.BitowerWrite { 48 s.BitowerWrite[i].Unlock() 49 } 50 } 51 52 func (s *DbStateMachine) LockBitowerWrite(i int) { 53 s.BitowerWrite[i].Lock() 54 } 55 56 func (s *DbStateMachine) UnlockBitowerWrite(i int) { 57 s.BitowerWrite[i].Unlock() 58 } 59 60 func (s *DbStateMachine) LockTask() { 61 s.TaskLock.Lock() 62 } 63 64 func (s *DbStateMachine) UnlockTask() { 65 s.TaskLock.Unlock() 66 } 67 68 func (s *DbStateMachine) AddBitpageFlushCount() { 69 s.bitpage.flushCount.Add(1) 70 } 71 72 func (s *DbStateMachine) GetBitpageFlushCount() uint64 { 73 return s.bitpage.flushCount.Load() 74 } 75 76 func (s *DbStateMachine) AddBitpageSplitCount() { 77 s.bitpage.splitCount.Add(1) 78 } 79 80 func (s *DbStateMachine) GetBitpageSplitCount() uint64 { 81 return s.bitpage.splitCount.Load() 82 } 83 84 func (s *DbStateMachine) SetDbHighPriority(v bool) { 85 for i := range s.BitowerHighPriority { 86 s.BitowerHighPriority[i].Store(v) 87 } 88 } 89 90 func (s *DbStateMachine) SetBitowerHighPriority(i int, v bool) { 91 s.BitowerHighPriority[i].Store(v) 92 } 93 94 func (s *DbStateMachine) WaitBitowerHighPriority(i int) { 95 for s.BitowerHighPriority[i].Load() { 96 time.Sleep(1 * time.Second) 97 } 98 }