github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/logtail/service/stacker.go (about) 1 // Copyright 2021 Matrix Origin 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 service 16 17 import ( 18 "sync" 19 "sync/atomic" 20 21 "github.com/matrixorigin/matrixone/pkg/pb/api" 22 ) 23 24 // TableStacker registers table repeatedly. 25 type TableStacker struct { 26 sync.RWMutex 27 tables map[TableID]*tableInfo 28 } 29 30 func NewTableStacker() *TableStacker { 31 return &TableStacker{ 32 tables: make(map[TableID]*tableInfo), 33 } 34 } 35 36 // ListTable takes a snapshot for all registered tables. 37 func (s *TableStacker) ListTable() []tableInfo { 38 s.RLock() 39 defer s.RUnlock() 40 41 list := make([]tableInfo, 0, len(s.tables)) 42 for _, info := range s.tables { 43 list = append(list, *info) 44 } 45 return list 46 } 47 48 // Register registers subscribed table. 49 func (s *TableStacker) Register(id TableID, table api.TableID) { 50 s.Lock() 51 defer s.Unlock() 52 53 if _, ok := s.tables[id]; !ok { 54 s.tables[id] = newTableInfo(id, table) 55 } 56 s.tables[id].Ref() 57 } 58 59 // Unregister decreases reference count for tables. 60 func (s *TableStacker) Unregister(ids ...TableID) { 61 s.Lock() 62 defer s.Unlock() 63 64 for _, id := range ids { 65 info, ok := s.tables[id] 66 if !ok { 67 continue 68 } 69 if info.Deref() == 0 { 70 delete(s.tables, id) 71 } 72 } 73 } 74 75 // tableInfo maintains a table's reference counter. 76 type tableInfo struct { 77 rc int32 78 id TableID 79 table api.TableID 80 } 81 82 func newTableInfo(id TableID, table api.TableID) *tableInfo { 83 return &tableInfo{ 84 rc: 0, 85 id: id, 86 table: table, 87 } 88 } 89 90 // Ref increases reference count. 91 func (t *tableInfo) Ref() int32 { 92 return atomic.AddInt32(&t.rc, 1) 93 } 94 95 // Deref decreases reference count. 96 func (t *tableInfo) Deref() int32 { 97 return atomic.AddInt32(&t.rc, -1) 98 }