github.com/songzhibin97/gkit@v1.2.13/distributed/task/meta.go (about)

     1  package task
     2  
     3  import "sync"
     4  
     5  // Meta task可以携带元信息
     6  type Meta struct {
     7  	meta map[string]interface{}
     8  	sync.RWMutex
     9  	safe bool
    10  }
    11  
    12  // NewMeta 生成meta信息
    13  func NewMeta(safe bool) *Meta {
    14  	return &Meta{
    15  		meta: make(map[string]interface{}),
    16  		safe: safe,
    17  	}
    18  }
    19  
    20  // Set 如果存在会覆盖
    21  func (m *Meta) Set(key string, value interface{}) {
    22  	if m.safe {
    23  		m.Lock()
    24  		defer m.Unlock()
    25  	}
    26  	m.meta[key] = value
    27  }
    28  
    29  func (m *Meta) Get(key string) (interface{}, bool) {
    30  	if m.safe {
    31  		m.RLock()
    32  		defer m.RUnlock()
    33  	}
    34  	v, ok := m.meta[key]
    35  	return v, ok
    36  }
    37  
    38  func (m *Meta) Range(f func(key string, value interface{})) {
    39  	if m.safe {
    40  		m.Lock()
    41  		defer m.Unlock()
    42  	}
    43  	for k, v := range m.meta {
    44  		f(k, v)
    45  	}
    46  }