type Mutex struct {}
func (m *Mutex) Lock() {}
func (m *Mutex) Unlock() {}
package main
import (
"sync"
"fmt"
)
type safeCounter struct {
number int
sync.Mutex
}
func (sc *safeCounter) Increment() {
sc.Lock()
sc.number++
sc.Unlock()
}
func (sc *safeCounter) Decrement() {
sc.Lock()
sc.number--
sc.Unlock()
}
func (sc *safeCounter) getNumber() int {
sc.Lock()
number := sc.number
sc.Unlock()
return number
}
func main() {
sc := new(safeCounter)
for i := 0; i < 100; i++ {
go sc.Increment()
go sc.Decrement()
}
fmt.Println(sc.getNumber())
}
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type MapCounter struct {
m map[int]int
sync.RWMutex
}
func (mapCounter *MapCounter) Reader(n int) {
for {
mapCounter.RLock()
v := mapCounter.m[rand.Intn(n)]
mapCounter.RUnlock()
fmt.Println(v)
time.Sleep(1 * time.Second)
}
}
func (mapCounter *MapCounter) Writer(n int) {
for i := 0; i < n; i++ {
mapCounter.Lock()
mapCounter.m[i] = i * 10
mapCounter.Unlock()
time.Sleep(1 * time.Second)
}
}
func main() {
mc := MapCounter{m: make(map[int]int)}
go mc.Writer(10)
go mc.Reader(10)
go mc.Reader(10)
time.Sleep(15 * time.Second)
}
package main
import (
"fmt"
"sync"
)
func main() {
once := sync.Once{}
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
once.Do(sayHello)
done <- true
}()
}
for i := 0; i < 10; i++ {
fmt.Println(<-done)
}
}
func sayHello() {
fmt.Println("Hello")
}
package main
import (
"fmt"
"sync"
)
func main() {
wg := sync.WaitGroup{}
for i := 0; i <= 5; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fmt.Println("Work done for ", i)
}(i)
}
wg.Wait()
}