Hacker News new | ask | show | jobs
by Jabbles 3898 days ago
You've been misinformed. The 2009 version of Effective Go stated, as it does now:

"This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance."

https://web.archive.org/web/20091113154825/http://golang.org...

2 comments

See the very first example of "channels" in that 2009 version:

"In the previous section we launched a sort in the background. A channel can allow the launching goroutine to wait for the sort to complete." ...

    c <- 1;  // Send a signal; value does not matter.
That's using a channel as a lock on shared data. Not seeing that in the new book. This is a step forward.

(What Go really needs is Rust's borrow checker and move semantics, so that when you communicate on a channel, the compiler checks that you're not sharing too much.)

Of course if you care about speed at all, you will stay away from Go's mutex's. Time your own code, it is shocking how slow they are. I haven't published my own test times, but with a quick search here's an example of a 10ms loop taking 2s with mutex's. http://www.arkxu.com/post/58998283664/performance-benchmark-...
A mutex held for up to 10ms on each iteration, over 500 iterations, averaging out to 2s doesn't seem surprising at all. In fact, this is quite expected. It would take considerably longer if the random sleep hit 10ms every time.

If you modify the code to release the lock before sleeping...

    func (c *Counter) add(ch chan int) {
            c.Lock()
            tmp := c.Num
            c.Unlock()
            tmp += 1
            time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
            c.Lock()
            c.Num = tmp
            c.Unlock()
            ch <- 1
    }
...and reacquiring it after, it still finishes in 10ms on my machine, as you'd expect. As you can see, the problem isn't so much that locks are inherently slow in Go, but rather the mutex, as the acqusition function name implies, is doing what it is supposed to do: Lock. What is true is that you have to be careful to use them properly.