Created
March 2, 2022 02:47
-
-
Save armando-couto/c8ef2ddbc4feb367e62e7043a5a807b8 to your computer and use it in GitHub Desktop.
If you’re already familiar with languages that handle concurrency through memory access synchronization, then you’ll probably immediately recognize Mutex. If you don’t count yourself among that group, don’t worry, Mutex is very easy to understand. Mutex stands for “mutual exclusion” and is a way to guard critical sections of your program. If yo…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
var count int | |
var lock sync.Mutex | |
increment := func() { | |
lock.Lock() | |
defer lock.Unlock() | |
count++ | |
fmt.Printf("Incrementing: %d\n", count) | |
} | |
decrement := func() { | |
lock.Lock() | |
defer lock.Unlock() | |
count-- | |
fmt.Printf("Decrementing: %d\n", count) | |
} | |
// Increment | |
var arithmetic sync.WaitGroup | |
for i := 0; i <= 5; i++ { | |
arithmetic.Add(1) | |
go func() { | |
defer arithmetic.Done() | |
increment() | |
}() | |
} | |
// Decrement | |
for i := 0; i <= 5; i++ { | |
arithmetic.Add(1) | |
go func() { | |
defer arithmetic.Done() | |
decrement() | |
}() | |
} | |
arithmetic.Wait() | |
fmt.Println("Arithmetic complete.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment