Mutex: Difference between revisions
→{{header|Go}}: added more substantive example.
(→{{header|Go}}: added more substantive example.) |
|||
Line 263:
=={{header|Go}}==
{{trans|E}}
<lang go>import "sync"▼
Here is an example use of a mutex, somewhat following the example of E. This code defines a slow incrementer, that reads a variable, then a significant amount of time later, writes an incremented value back to the variable. Two incrementers are started concurrently. Without the mutex, one would overwrite the other and the result would be 1. Using a mutex, as shown here, one waits for the other and the result is 2.
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
v := value
time.Sleep(1e8)
value = v+1
wg.Done()
}
func main() {
go slowInc()
▲ m.Lock() // locks
go slowInc()
▲ m.Unlock() // unlocks
wg.Wait()
fmt.Println(value)
}</lang>
Output:
<pre>
2
</pre>
Read-write mutex is provided by the <tt>sync.RWMutex</tt> type. For a code example using a RWMutex, see [http://rosettacode.org/wiki/Atomic_updates#RWMutex Atomic updates].
|