在Go语言中,实现并发控制通常使用goroutines和channels。goroutines是Go语言中的轻量级线程,可以在程序中同时运行多个goroutines来实现并发。channels则用于在goroutines之间传递数据和同步。
以下是在Ubuntu上使用Go语言实现并发控制的一些建议:
go关键字启动一个goroutine:package main
import (
"fmt"
"time"
)
func printNumbers() {
for i := 1; i <= 5; i++ {
fmt.Printf("Number: %d\n", i)
time.Sleep(1 * time.Second)
}
}
func main() {
go printNumbers()
time.Sleep(6 * time.Second)
}
sync.WaitGroup等待一组goroutines完成:package main
import (
"fmt"
"sync"
"time"
)
func printNumbers(wg *sync.WaitGroup) {
defer wg.Done()
for i := 1; i <= 5; i++ {
fmt.Printf("Number: %d\n", i)
time.Sleep(1 * time.Second)
}
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go printNumbers(&wg)
wg.Wait()
}
channel在goroutines之间传递数据:package main
import (
"fmt"
"time"
)
func printNumbers(numbers chan int) {
for num := range numbers {
fmt.Printf("Number: %d\n", num)
time.Sleep(1 * time.Second)
}
}
func main() {
numbers := make(chan int, 5)
for i := 1; i <= 5; i++ {
numbers <- i
}
close(numbers)
go printNumbers(numbers)
time.Sleep(6 * time.Second)
}
sync.Mutex实现互斥锁,保护共享资源:package main
import (
"fmt"
"sync"
"time"
)
var counter int
var mutex sync.Mutex
func incrementCounter() {
mutex.Lock()
defer mutex.Unlock()
counter++
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
incrementCounter()
}()
}
wg.Wait()
fmt.Printf("Counter: %d\n", counter)
}
这些示例展示了如何在Ubuntu上使用Go语言实现并发控制。你可以根据自己的需求选择合适的方法来实现并发控制。