Share a Go router between goroutines

Read a Go router from many goroutines at once, and guard it with a lock when its patterns change while it is in use.

Use this when more than one goroutine uses a router. A Patrun has no lock of its own. Find, FindExact, Collect, CollectExact, Get, List, String, and ToJSON only read it, so any number of goroutines may call them at once. Add and Remove change it, and must not run at the same time as any other call.

Most routers are built once and then only read, which needs nothing more: add the patterns, then share the router. If patterns change while it is in use, guard it with a sync.RWMutex:

pm := patrun.New()
var mu sync.RWMutex

mu.Lock()
pm.Add(map[string]string{"a": "1"}, s("A"))
mu.Unlock()

mu.RLock()
data, ok := pm.Find(map[string]string{"a": "1"})
mu.RUnlock()

*data // → A
ok    // → true

What to watch for #

A read under the read lock may run beside other reads, and a change under the write lock runs alone. The package's tests run with Go's race detector, which checks that concurrent reads are safe.

This page describes patrun 9.0.0 for JavaScript and 0.4.0 for Go. Edit this page · This page as Markdown