24

Java provides a very convenient idiom for synchronizing critical portions of code:

synchronized(someObject) {
    // do something really important all by myself with nobody bothering me
}

Or

public synchronized void doSomething() {
    // ...
}

What is the go equivalent?

(A quick search reveals: golang.org/pkg/sync/ - which seems (maybe I'm wrong) a bit too low level for general use.)

(Example of why I care about this: I need to send a message to multiple listeners via channels. Channels provide a good conduit for the data without having to synchronize anything, but when channels are added or removed I need to modify the list of channels, which might happen at any time must be able to deal with concurrency.)

Brad Peabody
  • 10,917
  • 9
  • 44
  • 63

3 Answers3

22

sync.Mutex is a mutual exclusion lock, it can provide a similar functionality to the synchronized java key-word (except that locks in java provide reentrant mutual exclusion) :

synchronized(someObject) {
    //   
}

Is equivalent to :

var l sync.Mutex

l.Lock()
//
l.Unlock()
Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
16

to extend off tarrsalah's answer.

You can add sync.Mutex to your object, allowing them to be directly locked and unlocked.

type MyObject struct{
    Number int
    sync.Mutex
}

func (m *MyObject)Increment(){
    m.Lock()
    defer m.Unlock()
    m.Number++
}

Defer'd commands will run at the end of the function, this way you know it gets both locked and unlocked, in bigger functions.

KittMedia
  • 7,368
  • 13
  • 34
  • 38
Ryan Carrier
  • 161
  • 1
  • 3
  • 2
    This answer is better because it mentions defer. Calling unlock() manually is prone to deadlocks – eshalev Oct 18 '17 at 06:58
9

A different solution to using a mutex is to use a channel to communicate listener changes.

A full example in this style looks like this. The interesting code is in FanOuter.

package main

import (
    "fmt"
    "time"
)

type Message int

type ListenerUpdate struct {
    Add      bool
    Listener chan Message
}

// FanOuter maintains listeners, and forwards messages from msgc
// to each of them. Updates on listc can add or remove a listener.
func FanOuter(msgc chan Message, listc chan ListenerUpdate) {
    lstrs := map[chan Message]struct{}{}
    for {
        select {
        case m := <-msgc:
            for k := range lstrs {
                k <- m
            }
        case lup := <-listc:
            if lup.Add {
                lstrs[lup.Listener] = struct{}{}
            } else {
                delete(lstrs, lup.Listener)
            }
        }
    }
}

func main() {
    msgc := make(chan Message)
    listc := make(chan ListenerUpdate)
    go FanOuter(msgc, listc)
    // Slowly add listeners, then slowly remove them.
    go func() {
        chans := make([]chan Message, 10)
        // Adding listeners.
        for i := range chans {
            chans[i] = make(chan Message)
            // A listener prints its id and any messages received.
            go func(i int, c chan Message) {
                for {
                    m := <-c
                    fmt.Printf("%d received %d\n", i, m)
                }
            }(i, chans[i])
            listc <- ListenerUpdate{true, chans[i]}
            time.Sleep(300 * time.Millisecond)
        }
        // Removing listeners.
        for i := range chans {
            listc <- ListenerUpdate{false, chans[i]}
            time.Sleep(300 * time.Millisecond)
        }
    }()
    // Every second send a message to the fanouter.
    for i := 0; i < 10; i++ {
        fmt.Println("About to send ", i)
        msgc <- Message(i)
        time.Sleep(1 * time.Second)
    }
}
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • This is a really good answer as it don't simply translate a lock from java to go, it uses go to resolve the initial problem you have with concurrency. It also clearly answers the problem stated .. +1 – Nikkolasg Jan 20 '16 at 20:26