onerciller
onerciller

Reputation: 800

what is sync (sync.RWMutex) in golang

I am looking gorilla context to source code. I don't understand what it does sync,mutex.Lock, mutex.Unlock exactly. it still is running when I removed mutex.Lock and Mutex.Unlock from source codes.

import (
    "net/http"
    "sync"
    "time"
)

var (
    mutex sync.RWMutex
    data  = make(map[*http.Request]map[interface{}]interface{})
    datat = make(map[*http.Request]int64)
)

// Set stores a value for a given key in a given request.
func Set(r *http.Request, key, val interface{}) {
    mutex.Lock()
    if data[r] == nil {
        data[r] = make(map[interface{}]interface{})
        datat[r] = time.Now().Unix()
    }
    data[r][key] = val
    mutex.Unlock()
}

Upvotes: 0

Views: 1315

Answers (1)

nothingmuch
nothingmuch

Reputation: 1516

Gorrila's context associates data structures with one another by means of a map, but maps are not safe for concurrent use in go.

To allow multiple goroutines to safely access the same map, the mutex is used to ensure only one goro has write access to the map at any given time.

However, since maps are safe for concurrent reads in go, RWMutex allows shared concurrent access for reading data off of the map by splitting up the two access roles, sothat at any point in time there are either no lockers, a single write locker, or one or more read lockers currently holding the mutex.

Upvotes: 3

Related Questions