ruk·si

🐹 Go
Synchronization

Updated at 2014-01-20 10:48

Go sync package offers ways to implement synchronization between goroutines.

You should be using channels for basic goroutine communication though.

sync.Mutex resources to be accessed by one goroutine at a time.

package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

type Counter struct {
    counter int
    mutex   sync.Mutex
}

func (c *Counter) Add(number int) {
    c.mutex.Lock()
    defer c.mutex.Unlock()
    c.counter += number
}

func (c *Counter) Get() int {
    c.mutex.Lock()
    defer c.mutex.Unlock()
    return c.counter
}

func main() {
    counter := Counter{}
    // start a lot of goroutines that all try to get the lock and increment the number
    for r := 0; r < 100; r++ {
        go func() {
            for {
                counter.Add(1)
                runtime.Gosched() // allow other coroutines to proceed
            }
        }()
    }
    runtime.Gosched()                  // allow others to execute if any are waiting
    time.Sleep(100 * time.Millisecond) // also give some time to build up the numbers
    fmt.Println("counter:", counter.Get())
    // result depends on the environment
}

Source