I should add: using channels often means the mutex is not required.
Imagine, for example, that you want a concurrency-safe counter (that
multiple goroutines can read, increment and decrement). You can put the
counter value into a buffered channel:
counter := make(chan int, 1)
counter <- 0
Then you pull the value out of channel while you're working on it, and put
it back when you're finished.
// Read counter
cv := <- counter
fmt.Println("Counter is %d", cv)
counter <- cv
// Increment counter
counter <- (<-counter + 1)
This is all safe because only one goroutine has possession of the counter
value at any time. Just make sure you always put it back (it can be
helpful to write functions to do the accessing, and use 'defer' to put the
value back)
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/c6de9b79-857c-41fd-bcb2-f62f1ddd7e71n%40googlegroups.com.