sync
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package sync provides basic synchronization primitives such as mutualexclusion locks. Other than theOnce andWaitGroup types, most are intendedfor use by low-level library routines. Higher-level synchronization isbetter done via channels and communication.
Values containing the types defined in this package should not be copied.
Index¶
- func OnceFunc(f func()) func()
- func OnceValue[T any](f func() T) func() T
- func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)
- type Cond
- type Locker
- type Map
- func (m *Map) Clear()
- func (m *Map) CompareAndDelete(key, old any) (deleted bool)
- func (m *Map) CompareAndSwap(key, old, new any) (swapped bool)
- func (m *Map) Delete(key any)
- func (m *Map) Load(key any) (value any, ok bool)
- func (m *Map) LoadAndDelete(key any) (value any, loaded bool)
- func (m *Map) LoadOrStore(key, value any) (actual any, loaded bool)
- func (m *Map) Range(f func(key, value any) bool)
- func (m *Map) Store(key, value any)
- func (m *Map) Swap(key, value any) (previous any, loaded bool)
- type Mutex
- type Once
- type Pool
- type RWMutex
- type WaitGroup
Examples¶
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcOnceFunc¶added ingo1.21.0
func OnceFunc(f func()) func()
OnceFunc returns a function that invokes f only once. The returned functionmay be called concurrently.
If f panics, the returned function will panic with the same value on every call.
funcOnceValue¶added ingo1.21.0
func OnceValue[Tany](f func() T) func() T
OnceValue returns a function that invokes f only once and returns the valuereturned by f. The returned function may be called concurrently.
If f panics, the returned function will panic with the same value on every call.
Example¶
This example uses OnceValue to perform an "expensive" computation just once,even when used concurrently.
package mainimport ("fmt""sync")func main() {once := sync.OnceValue(func() int {sum := 0for i := 0; i < 1000; i++ {sum += i}fmt.Println("Computed once:", sum)return sum})done := make(chan bool)for i := 0; i < 10; i++ {go func() {const want = 499500got := once()if got != want {fmt.Println("want", want, "got", got)}done <- true}()}for i := 0; i < 10; i++ {<-done}}Output:Computed once: 499500
funcOnceValues¶added ingo1.21.0
func OnceValues[T1, T2any](f func() (T1, T2)) func() (T1, T2)
OnceValues returns a function that invokes f only once and returns the valuesreturned by f. The returned function may be called concurrently.
If f panics, the returned function will panic with the same value on every call.
Example¶
This example uses OnceValues to read a file just once.
package mainimport ("fmt""os""sync")func main() {once := sync.OnceValues(func() ([]byte, error) {fmt.Println("Reading file once")return os.ReadFile("example_test.go")})done := make(chan bool)for i := 0; i < 10; i++ {go func() {data, err := once()if err != nil {fmt.Println("error:", err)}_ = data // Ignore the data for this exampledone <- true}()}for i := 0; i < 10; i++ {<-done}}Output:Reading file once
Types¶
typeCond¶
type Cond struct {// L is held while observing or changing the conditionLLocker// contains filtered or unexported fields}Cond implements a condition variable, a rendezvous pointfor goroutines waiting for or announcing the occurrenceof an event.
Each Cond has an associated Locker L (often a*Mutex or*RWMutex),which must be held when changing the condition andwhen calling theCond.Wait method.
A Cond must not be copied after first use.
In the terminology ofthe Go memory model, Cond arranges thata call toCond.Broadcast orCond.Signal “synchronizes before” any Wait callthat it unblocks.
For many simple use cases, users will be better off using channels than aCond (Broadcast corresponds to closing a channel, and Signal corresponds tosending on a channel).
For more on replacements forsync.Cond, seeRoberto Clapis's series onadvanced concurrency patterns, as well asBryan Mills's talk on concurrencypatterns.
func (*Cond)Broadcast¶
func (c *Cond) Broadcast()
Broadcast wakes all goroutines waiting on c.
It is allowed but not required for the caller to hold c.Lduring the call.
func (*Cond)Signal¶
func (c *Cond) Signal()
Signal wakes one goroutine waiting on c, if there is any.
It is allowed but not required for the caller to hold c.Lduring the call.
Signal() does not affect goroutine scheduling priority; if other goroutinesare attempting to lock c.L, they may be awoken before a "waiting" goroutine.
func (*Cond)Wait¶
func (c *Cond) Wait()
Wait atomically unlocks c.L and suspends executionof the calling goroutine. After later resuming execution,Wait locks c.L before returning. Unlike in other systems,Wait cannot return unless awoken byCond.Broadcast orCond.Signal.
Because c.L is not locked while Wait is waiting, the callertypically cannot assume that the condition is true whenWait returns. Instead, the caller should Wait in a loop:
c.L.Lock()for !condition() { c.Wait()}... make use of condition ...c.L.Unlock()typeLocker¶
type Locker interface {Lock()Unlock()}A Locker represents an object that can be locked and unlocked.
typeMap¶added ingo1.9
type Map struct {// contains filtered or unexported fields}Map is like a Go map[any]any but is safe for concurrent useby multiple goroutines without additional locking or coordination.Loads, stores, and deletes run in amortized constant time.
The Map type is specialized. Most code should use a plain Go map instead,with separate locking or coordination, for better type safety and to make iteasier to maintain other invariants along with the map content.
The Map type is optimized for two common use cases: (1) when the entry for a givenkey is only ever written once but read many times, as in caches that only grow,or (2) when multiple goroutines read, write, and overwrite entries for disjointsets of keys. In these two cases, use of a Map may significantly reduce lockcontention compared to a Go map paired with a separateMutex orRWMutex.
The zero Map is empty and ready for use. A Map must not be copied after first use.
In the terminology ofthe Go memory model, Map arranges that a write operation“synchronizes before” any read operation that observes the effect of the write, whereread and write operations are defined as follows.Map.Load,Map.LoadAndDelete,Map.LoadOrStore,Map.Swap,Map.CompareAndSwap,andMap.CompareAndDelete are read operations;Map.Delete,Map.LoadAndDelete,Map.Store, andMap.Swap are write operations;Map.LoadOrStore is a write operation when it returns loaded set to false;Map.CompareAndSwap is a write operation when it returns swapped set to true;andMap.CompareAndDelete is a write operation when it returns deleted set to true.
func (*Map)Clear¶added ingo1.23.0
func (m *Map) Clear()
Clear deletes all the entries, resulting in an empty Map.
func (*Map)CompareAndDelete¶added ingo1.20
CompareAndDelete deletes the entry for key if its value is equal to old.The old value must be of a comparable type.
If there is no current value for key in the map, CompareAndDeletereturns false (even if the old value is the nil interface value).
func (*Map)CompareAndSwap¶added ingo1.20
CompareAndSwap swaps the old and new values for keyif the value stored in the map is equal to old.The old value must be of a comparable type.
func (*Map)Load¶added ingo1.9
Load returns the value stored in the map for a key, or nil if novalue is present.The ok result indicates whether value was found in the map.
func (*Map)LoadAndDelete¶added ingo1.15
LoadAndDelete deletes the value for a key, returning the previous value if any.The loaded result reports whether the key was present.
func (*Map)LoadOrStore¶added ingo1.9
LoadOrStore returns the existing value for the key if present.Otherwise, it stores and returns the given value.The loaded result is true if the value was loaded, false if stored.
func (*Map)Range¶added ingo1.9
Range calls f sequentially for each key and value present in the map.If f returns false, range stops the iteration.
Range does not necessarily correspond to any consistent snapshot of the Map'scontents: no key will be visited more than once, but if the value for any keyis stored or deleted concurrently (including by f), Range may reflect anymapping for that key from any point during the Range call. Range does notblock other methods on the receiver; even f itself may call any method on m.
Range may be O(N) with the number of elements in the map even if f returnsfalse after a constant number of calls.
typeMutex¶
type Mutex struct {// contains filtered or unexported fields}A Mutex is a mutual exclusion lock.The zero value for a Mutex is an unlocked mutex.
A Mutex must not be copied after first use.
In the terminology ofthe Go memory model,the n'th call toMutex.Unlock “synchronizes before” the m'th call toMutex.Lockfor any n < m.A successful call toMutex.TryLock is equivalent to a call to Lock.A failed call to TryLock does not establish any “synchronizes before”relation at all.
func (*Mutex)Lock¶
func (m *Mutex) Lock()
Lock locks m.If the lock is already in use, the calling goroutineblocks until the mutex is available.
typeOnce¶
type Once struct {// contains filtered or unexported fields}Once is an object that will perform exactly one action.
A Once must not be copied after first use.
In the terminology ofthe Go memory model,the return from f “synchronizes before”the return from any call of once.Do(f).
Example¶
package mainimport ("fmt""sync")func main() {var once sync.OnceonceBody := func() {fmt.Println("Only once")}done := make(chan bool)for i := 0; i < 10; i++ {go func() {once.Do(onceBody)done <- true}()}for i := 0; i < 10; i++ {<-done}}Output:Only once
func (*Once)Do¶
func (o *Once) Do(f func())
Do calls the function f if and only if Do is being called for thefirst time for this instance ofOnce. In other words, given
var once Once
if once.Do(f) is called multiple times, only the first call will invoke f,even if f has a different value in each invocation. A new instance ofOnce is required for each function to execute.
Do is intended for initialization that must be run exactly once. Since fis niladic, it may be necessary to use a function literal to capture thearguments to a function to be invoked by Do:
config.once.Do(func() { config.init(filename) })Because no call to Do returns until the one call to f returns, if f causesDo to be called, it will deadlock.
If f panics, Do considers it to have returned; future calls of Do returnwithout calling f.
typePool¶added ingo1.3
type Pool struct {// New optionally specifies a function to generate// a value when Get would otherwise return nil.// It may not be changed concurrently with calls to Get.New func()any// contains filtered or unexported fields}A Pool is a set of temporary objects that may be individually saved andretrieved.
Any item stored in the Pool may be removed automatically at any time withoutnotification. If the Pool holds the only reference when this happens, theitem might be deallocated.
A Pool is safe for use by multiple goroutines simultaneously.
Pool's purpose is to cache allocated but unused items for later reuse,relieving pressure on the garbage collector. That is, it makes it easy tobuild efficient, thread-safe free lists. However, it is not suitable for allfree lists.
An appropriate use of a Pool is to manage a group of temporary itemssilently shared among and potentially reused by concurrent independentclients of a package. Pool provides a way to amortize allocation overheadacross many clients.
An example of good use of a Pool is in the fmt package, which maintains adynamically-sized store of temporary output buffers. The store scales underload (when many goroutines are actively printing) and shrinks whenquiescent.
On the other hand, a free list maintained as part of a short-lived object isnot a suitable use for a Pool, since the overhead does not amortize well inthat scenario. It is more efficient to have such objects implement their ownfree list.
A Pool must not be copied after first use.
In the terminology ofthe Go memory model, a call to Put(x) “synchronizes before”a call toPool.Get returning that same value x.Similarly, a call to New returning x “synchronizes before”a call to Get returning that same value x.
Example¶
package mainimport ("bytes""io""os""sync""time")var bufPool = sync.Pool{New: func() any {// The Pool's New function should generally only return pointer// types, since a pointer can be put into the return interface// value without an allocation:return new(bytes.Buffer)},}// timeNow is a fake version of time.Now for tests.func timeNow() time.Time {return time.Unix(1136214245, 0)}func Log(w io.Writer, key, val string) {b := bufPool.Get().(*bytes.Buffer)b.Reset()// Replace this with time.Now() in a real logger.b.WriteString(timeNow().UTC().Format(time.RFC3339))b.WriteByte(' ')b.WriteString(key)b.WriteByte('=')b.WriteString(val)w.Write(b.Bytes())bufPool.Put(b)}func main() {Log(os.Stdout, "path", "/search?q=flowers")}Output:2006-01-02T15:04:05Z path=/search?q=flowers
func (*Pool)Get¶added ingo1.3
Get selects an arbitrary item from thePool, removes it from thePool, and returns it to the caller.Get may choose to ignore the pool and treat it as empty.Callers should not assume any relation between values passed toPool.Put andthe values returned by Get.
If Get would otherwise return nil and p.New is non-nil, Get returnsthe result of calling p.New.
typeRWMutex¶
type RWMutex struct {// contains filtered or unexported fields}A RWMutex is a reader/writer mutual exclusion lock.The lock can be held by an arbitrary number of readers or a single writer.The zero value for a RWMutex is an unlocked mutex.
A RWMutex must not be copied after first use.
If any goroutine callsRWMutex.Lock while the lock is already held byone or more readers, concurrent calls toRWMutex.RLock will block untilthe writer has acquired (and released) the lock, to ensure thatthe lock eventually becomes available to the writer.Note that this prohibits recursive read-locking.ARWMutex.RLock cannot be upgraded into aRWMutex.Lock,nor can aRWMutex.Lock be downgraded into aRWMutex.RLock.
In the terminology ofthe Go memory model,the n'th call toRWMutex.Unlock “synchronizes before” the m'th call to Lockfor any n < m, just as forMutex.For any call to RLock, there exists an n such thatthe n'th call to Unlock “synchronizes before” that call to RLock,and the corresponding call toRWMutex.RUnlock “synchronizes before”the n+1'th call to Lock.
func (*RWMutex)Lock¶
func (rw *RWMutex) Lock()
Lock locks rw for writing.If the lock is already locked for reading or writing,Lock blocks until the lock is available.
func (*RWMutex)RLock¶
func (rw *RWMutex) RLock()
RLock locks rw for reading.
It should not be used for recursive read locking; a blocked Lockcall excludes new readers from acquiring the lock. See thedocumentation on theRWMutex type.
func (*RWMutex)RLocker¶
RLocker returns aLocker interface that implementsthe [Locker.Lock] and [Locker.Unlock] methods by calling rw.RLock and rw.RUnlock.
func (*RWMutex)RUnlock¶
func (rw *RWMutex) RUnlock()
RUnlock undoes a singleRWMutex.RLock call;it does not affect other simultaneous readers.It is a run-time error if rw is not locked for readingon entry to RUnlock.
func (*RWMutex)TryLock¶added ingo1.18
TryLock tries to lock rw for writing and reports whether it succeeded.
Note that while correct uses of TryLock do exist, they are rare,and use of TryLock is often a sign of a deeper problemin a particular use of mutexes.
func (*RWMutex)TryRLock¶added ingo1.18
TryRLock tries to lock rw for reading and reports whether it succeeded.
Note that while correct uses of TryRLock do exist, they are rare,and use of TryRLock is often a sign of a deeper problemin a particular use of mutexes.
func (*RWMutex)Unlock¶
func (rw *RWMutex) Unlock()
Unlock unlocks rw for writing. It is a run-time error if rw isnot locked for writing on entry to Unlock.
As with Mutexes, a lockedRWMutex is not associated with a particulargoroutine. One goroutine mayRWMutex.RLock (RWMutex.Lock) a RWMutex and thenarrange for another goroutine toRWMutex.RUnlock (RWMutex.Unlock) it.
typeWaitGroup¶
type WaitGroup struct {// contains filtered or unexported fields}A WaitGroup is a counting semaphore typically used to waitfor a group of goroutines or tasks to finish.
Typically, a main goroutine will start tasks, each in a newgoroutine, by callingWaitGroup.Go and then wait for all tasks tocomplete by callingWaitGroup.Wait. For example:
var wg sync.WaitGroupwg.Go(task1)wg.Go(task2)wg.Wait()
A WaitGroup may also be used for tracking tasks without using Go tostart new goroutines by usingWaitGroup.Add andWaitGroup.Done.
The previous example can be rewritten using explicitly createdgoroutines along with Add and Done:
var wg sync.WaitGroupwg.Add(1)go func() {defer wg.Done()task1()}()wg.Add(1)go func() {defer wg.Done()task2()}()wg.Wait()This pattern is common in code that predatesWaitGroup.Go.
A WaitGroup must not be copied after first use.
Example¶
This example fetches several URLs concurrently,using a WaitGroup to block until all the fetches are complete.
package mainimport ("sync")type httpPkg struct{}func (httpPkg) Get(url string) {}var http httpPkgfunc main() {var wg sync.WaitGroupvar urls = []string{"http://www.golang.org/","http://www.google.com/","http://www.example.com/",}for _, url := range urls {// Launch a goroutine to fetch the URL.wg.Go(func() {// Fetch the URL.http.Get(url)})}// Wait for all HTTP fetches to complete.wg.Wait()}Example (AddAndDone)¶
This example is equivalent to the main example, but uses Add/Doneinstead of Go.
package mainimport ("sync")type httpPkg struct{}func (httpPkg) Get(url string) {}var http httpPkgfunc main() {var wg sync.WaitGroupvar urls = []string{"http://www.golang.org/","http://www.google.com/","http://www.example.com/",}for _, url := range urls {// Increment the WaitGroup counter.wg.Add(1)// Launch a goroutine to fetch the URL.go func(url string) {// Decrement the counter when the goroutine completes.defer wg.Done()// Fetch the URL.http.Get(url)}(url)}// Wait for all HTTP fetches to complete.wg.Wait()}func (*WaitGroup)Add¶
Add adds delta, which may be negative, to theWaitGroup task counter.If the counter becomes zero, all goroutines blocked onWaitGroup.Wait are released.If the counter goes negative, Add panics.
Callers should preferWaitGroup.Go.
Note that calls with a positive delta that occur when the counter is zeromust happen before a Wait. Calls with a negative delta, or calls with apositive delta that start when the counter is greater than zero, may happenat any time.Typically this means the calls to Add should execute before the statementcreating the goroutine or other event to be waited for.If a WaitGroup is reused to wait for several independent sets of events,new Add calls must happen after all previous Wait calls have returned.See the WaitGroup example.
func (*WaitGroup)Done¶
func (wg *WaitGroup) Done()
Done decrements theWaitGroup task counter by one.It is equivalent to Add(-1).
Callers should preferWaitGroup.Go.
In the terminology ofthe Go memory model, a call to Done"synchronizes before" the return of any Wait call that it unblocks.
func (*WaitGroup)Go¶added ingo1.25.0
func (wg *WaitGroup) Go(f func())
Go calls f in a new goroutine and adds that task to theWaitGroup.When f returns, the task is removed from the WaitGroup.
The function f must not panic.
If the WaitGroup is empty, Go must happen before aWaitGroup.Wait.Typically, this simply means Go is called to start tasks before Wait is called.If the WaitGroup is not empty, Go may happen at any time.This means a goroutine started by Go may itself call Go.If a WaitGroup is reused to wait for several independent sets of tasks,new Go calls must happen after all previous Wait calls have returned.
In the terminology ofthe Go memory model, the return from f"synchronizes before" the return of any Wait call that it unblocks.