Golang synchronization: Difference between revisions

From wikinotes
(Created page with "Synchronization tools are used to synchronize multiple concurrent codepaths so that your program can continue synchronously. = WaitGroups = <blockquote> WaitGroups are global...")
 
No edit summary
Line 1: Line 1:
Synchronization tools are used to synchronize multiple concurrent codepaths so that your program can continue synchronously.
Synchronization tools are used to synchronize multiple concurrent codepaths so that your program can continue synchronously.
= Documentation =
<blockquote>
{| class="wikitable"
|-
| <code>sync</code> docs || https://pkg.go.dev/sync
|-
|}
</blockquote><!-- Documentation -->
= Mutexes =
<blockquote>
== RWMutex ==
<blockquote>
Variation of a mutex where:
* any number of items can acquire a lock for reading
* only one item can acquire lock for writing
* you cannot write while any other lock is reading
<syntaxhighlight lang="go">
import "sync"
var lock = RWMutex{}
// lock/unlock for reading
lock.RLock()
lock.RUnlock()
// lock/unlock for writing
lock.Lock()
lock.Unlock()
</syntaxhighlight>
It would be sensible to unlcok in <code>defer</code>red functions.
</blockquote><!-- RWMutex -->
</blockquote><!-- Mutexes -->


= WaitGroups =
= WaitGroups =

Revision as of 19:26, 6 June 2022

Synchronization tools are used to synchronize multiple concurrent codepaths so that your program can continue synchronously.

Documentation

sync docs https://pkg.go.dev/sync

Mutexes

RWMutex

Variation of a mutex where:

  • any number of items can acquire a lock for reading
  • only one item can acquire lock for writing
  • you cannot write while any other lock is reading
import "sync"

var lock = RWMutex{}

// lock/unlock for reading
lock.RLock()
lock.RUnlock()

// lock/unlock for writing
lock.Lock()
lock.Unlock()

It would be sensible to unlcok in deferred functions.

WaitGroups

WaitGroups are global threadsafe counters that are incremented/decremented.

wg = sync.WaitGroup{}

wg.Add(3)  // add 3x increments to countdown
wg.Done()  // decrement waitgroup by one
wg.Wait()  // wait for waitgroup to reach 0
// wait-groups are threadsafe proxy objects, intended to be globally accessible
var wg = sync.WaitGroup{}

func printHi() {
    fmt.Println("hi")
    wg.Done()
}

func main() {
    wg.Add(3)
    for i=0; i<3; i++ {
        go printHi()
    }
    wg.Wait()
    fmt.Println("bye")
}