?Go???,????????????,??????????:
- ?????(Mutex):??????????,???????????????(goroutine)?????????Go?
sync
????Mutex
???,????????????Lock()
????,Unlock()
?????
package main import ( "fmt" "sync" ) var counter int var lock sync.Mutex func increment() { lock.Lock() counter++ lock.Unlock() } func main() { wg := sync.WaitGroup{} for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() increment() }() } wg.Wait() fmt.Println("Counter:", counter) }
- ?????(RWMutex):?????????????????,???????????????Go?
sync
????RWMutex
???,????????????RLock()
?????,RUnlock()
?????,Lock()
?????,Unlock()
??????
package main
import (
"fmt"
"sync"
)
var data map[string]string
var rwLock sync.RWMutex
func readData(key string) {
rwLock.RLock()
value := data[key]
rwLock.RUnlock()
fmt.Println("Read:", value)
}
func writeData(key, value string) {
rwLock.Lock()
data[key] = value
rwLock.Unlock()
}
func main() {
data = https://www.yisu.com/ask/make(map[string]string)"hljs">func(i int) {
defer wg.Done()
key := fmt.Sprintf("key%d", i)
value := fmt.Sprintf("value%d", i)
writeData(key, value)
}(i)
}
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key := fmt.Sprintf("key%d", i)
readData(key)
}(i)
}
wg.Wait()
}
- ??????(atomic):???????????????,????????????????????Go?
sync/atomic
????????????,?AddInt32()
?CompareAndSwapInt32()
??
package main import ( "fmt" "sync" "sync/atomic" ) var counter int32 var wg sync.WaitGroup func increment() { atomic.AddInt32(&counter, 1) } func main() { for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() increment() }() } wg.Wait() fmt.Println("Counter:", counter) }
- ????(channel):???Go????????????,??????????????????,??????????????????
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, ch chan int) {
defer wg.Done()
for i := range ch {
fmt.Println("Received:", i)
}
}
func main() {
ch := make(chan int, 100)
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go worker(&wg, ch)
}
for i := 0; i < 100; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
??????????,???????,???????????????????,??????????????????