在Go語言中,全局變量可以在并發編程中使用,但是需要注意正確地處理并發訪問。Go語言提供了一些同步原語,如互斥鎖(Mutex)、讀寫鎖(RWMutex)和通道(Channel),以確保在并發環境下對全局變量的安全訪問。
使用互斥鎖(Mutex)保護全局變量:
package main
import (
"fmt"
"sync"
)
var (
counter int
mutex sync.Mutex
)
func increment() {
mutex.Lock()
counter++
mutex.Unlock()
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
使用讀寫鎖(RWMutex)保護全局變量:
package main
import (
"fmt"
"sync"
)
var (
data map[string]int
rwMutex sync.RWMutex
)
func readData() int {
rwMutex.RLock()
defer rwMutex.RUnlock()
return data["key"]
}
func writeData(key string, value int) {
rwMutex.Lock()
defer rwMutex.Unlock()
data[key] = value
}
func main() {
data = make(map[string]int)
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
writeData("key", 1)
}()
}
wg.Wait()
fmt.Println("Data:", readData())
}
使用通道(Channel)傳遞數據:
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, ch chan int) {
defer wg.Done()
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
}
func main() {
var wg sync.WaitGroup
ch := make(chan int)
wg.Add(1)
go worker(&wg, ch)
counter := 0
for value := range ch {
counter += value
}
wg.Wait()
fmt.Println("Counter:", counter)
}
總之,Go語言的全局變量可以在并發編程中使用,但需要使用適當的同步原語來確保數據的一致性和安全性。