Mutex: Difference between revisions

684 bytes added ,  13 years ago
→‎{{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.
<lang go>importpackage "sync"main
 
import (
"fmt"
"sync"
"time"
)
 
var value int
var m sync.Mutex
var wg sync.WaitGroup
 
func slowInc() {
m.Lock() // locks
v := value
time.Sleep(1e8)
value = v+1
m.Unlock() // unlocks
wg.Done()
}
 
func main() {
m := new(syncwg.MutexAdd(2)
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].
 
1,707

edits