typestar

RWMutex en Go

Muchos lectores o un solo escritor, cuando dominan las lecturas.

type Table struct {
    mu   sync.RWMutex
    rows map[string]int
}

func NewTable() *Table {
    return &Table{rows: make(map[string]int)}
}

func (t *Table) Set(key string, value int) {
    t.mu.Lock()
    defer t.mu.Unlock()
    t.rows[key] = value
}

func (t *Table) Get(key string) (int, bool) {
    t.mu.RLock()
    defer t.mu.RUnlock()
    value, ok := t.rows[key]
    return value, ok
}

Cómo funciona

  1. RLock puede sostenerse en concurrente; Lock excluye a todos.
  2. Desbloquea siempre con defer, para que un return no lo salte.
  3. Embeber el mutex en el struct los mantiene juntos.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
21
Caracteres a escribir
354
Tokens
124
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 71 segundos.

Escribe este fragmento

Paso 2 de 5 en Sincronización; paso 15 de 25 en Concurrencia.

← Anterior Siguiente →