goroutines 및 동기화 패키지에 대해 읽었습니다. 내 질문은 ... 다른 goroutines의 데이터에 대한 쓰기를 읽을 때 항상 잠금을 해제해야합니까?goroutine 잠금 및 잠금 해제
예를 들어 제가 설정에서 읽고 싶은 다른 goroutines에
config := make(map[string]string)
그럼 내 서버에 변수가있다. 동기화를 사용하지 않고 읽는 것이 안전합니까 아니면 그렇지 않은가요?
동기화 패키지를 사용하여 작성해야합니다. 하지만 난
type Cache interface {
Get(key string) interface{}
Put(key string, expires int64, value interface{})
}
// MemoryCache represents a memory type of cache
type MemoryCache struct {
c map[string]*MemoryCacheValue
rw sync.RWMutex
}
// MemoryCacheValue represents a memory cache value
type MemoryCacheValue struct {
value interface{}
expires int64
}
// NewMemoryCache creates a new memory cache
func NewMemoryCache() Cache {
return &MemoryCache{
c: make(map[string]*MemoryCacheValue),
}
}
// Get stores something into the cache
func (m *MemoryCache) Get(key string) interface{} {
if v, ok := m.c[key]; ok {
return v
}
return nil
}
// Put retrieves something from the cache
func (m *MemoryCache) Put(key string, expires int64, value interface{}) {
m.rw.Lock()
m.c[key] = &MemoryCacheValue{
value,
time.Now().Unix() + expires,
}
m.rw.Unlock()
}
내가 안전 여기에 행동하고 간단한 메모리 캐시 시스템이 아니면 내가 아직도 내가 읽기 전용으로 할 때 잠금 해제를 잠글 필요가
예를 들어읽기에 대한 확실하지 않다?
나는 가짜 경주 예를 제거한다. 첫 번째 예제에서'o'와'm'을 섞어서 Mutex 메서드를 포함 된 필드로 참조하면서 '뮤텍스'로 정의합니다. – JimB
권장 사항 당 수정 됨. – Kaedys