github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/cache/lfucache/read_state.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 lfucache
    16  
    17  import "sync/atomic"
    18  
    19  type readState struct {
    20  	refcnt    int32
    21  	memtables flushableList
    22  	arrtable  *flushableEntry
    23  }
    24  
    25  func (s *readState) ref() {
    26  	atomic.AddInt32(&s.refcnt, 1)
    27  }
    28  
    29  func (s *readState) unref() {
    30  	if atomic.AddInt32(&s.refcnt, -1) != 0 {
    31  		return
    32  	}
    33  
    34  	if s.arrtable != nil {
    35  		s.arrtable.readerUnref()
    36  	}
    37  
    38  	for _, t := range s.memtables {
    39  		t.readerUnref()
    40  	}
    41  }
    42  
    43  func (s *shard) loadReadState() *readState {
    44  	s.readState.RLock()
    45  	state := s.readState.val
    46  	state.ref()
    47  	s.readState.RUnlock()
    48  	return state
    49  }
    50  
    51  func (s *shard) updateReadStateLocked() {
    52  	rs := &readState{
    53  		refcnt:    1,
    54  		memtables: s.mu.memQueue,
    55  		arrtable:  s.mu.arrtable,
    56  	}
    57  
    58  	if rs.arrtable != nil {
    59  		rs.arrtable.readerRef()
    60  	}
    61  
    62  	for _, mem := range rs.memtables {
    63  		mem.readerRef()
    64  	}
    65  
    66  	s.readState.Lock()
    67  	old := s.readState.val
    68  	s.readState.val = rs
    69  	s.readState.Unlock()
    70  
    71  	if old != nil {
    72  		old.unref()
    73  	}
    74  
    75  	s.setMemtableNum(int32(len(rs.memtables)))
    76  }