github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/sync/status_pool.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2016 The Gogs Authors. All rights reserved.
     7  // Use of this source code is governed by a MIT-style
     8  // license that can be found in the LICENSE file.
     9  
    10  package sync
    11  
    12  import (
    13  	"sync"
    14  )
    15  
    16  // StatusTable is a table maintains true/false values.
    17  //
    18  // This table is particularly useful for un/marking and checking values
    19  // in different goroutines.
    20  type StatusTable struct {
    21  	lock sync.RWMutex
    22  	pool map[string]struct{}
    23  }
    24  
    25  // NewStatusTable initializes and returns a new StatusTable object.
    26  func NewStatusTable() *StatusTable {
    27  	return &StatusTable{
    28  		pool: make(map[string]struct{}),
    29  	}
    30  }
    31  
    32  // StartIfNotRunning sets value of given name to true if not already in pool.
    33  // Returns whether set value was set to true
    34  func (p *StatusTable) StartIfNotRunning(name string) bool {
    35  	p.lock.Lock()
    36  	_, ok := p.pool[name]
    37  	if !ok {
    38  		p.pool[name] = struct{}{}
    39  	}
    40  	p.lock.Unlock()
    41  	return !ok
    42  }
    43  
    44  // Start sets value of given name to true in the pool.
    45  func (p *StatusTable) Start(name string) {
    46  	p.lock.Lock()
    47  	p.pool[name] = struct{}{}
    48  	p.lock.Unlock()
    49  }
    50  
    51  // Stop sets value of given name to false in the pool.
    52  func (p *StatusTable) Stop(name string) {
    53  	p.lock.Lock()
    54  	delete(p.pool, name)
    55  	p.lock.Unlock()
    56  }
    57  
    58  // IsRunning checks if value of given name is set to true in the pool.
    59  func (p *StatusTable) IsRunning(name string) bool {
    60  	p.lock.RLock()
    61  	_, ok := p.pool[name]
    62  	p.lock.RUnlock()
    63  	return ok
    64  }