在Golang中,实现并发控制的主要方法是使用goroutines和channels。goroutines是Go语言中的轻量级线程,可以让你同时运行多个函数。channels则用于在goroutines之间传递数据和控制它们的执行顺序。
以下是在CentOS上使用Golang实现并发控制的几种方法:
go关键字启动goroutines: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)
}
package main
import (
"fmt"
"sync"
)
func printNumbers(wg *sync.WaitGroup) {
defer wg.Done()
for i := 1; i <= 5; i++ {
fmt.Printf("Number: %d\n", i)
}
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go printNumbers(&wg)
wg.Wait()
}
package main
import (
"fmt"
"sync"
"time"
)
func printNumbers(wg *sync.WaitGroup, ch chan struct{}) {
defer wg.Done()
ch <- struct{}{}
fmt.Println("Number:", <-ch)
}
func main() {
var wg sync.WaitGroup
ch := make(chan struct{}, 3) // 限制最多同时运行3个goroutines
for i := 1; i <= 5; i++ {
wg.Add(1)
go printNumbers(&wg, ch)
time.Sleep(1 * time.Second)
}
wg.Wait()
}
sync.Mutex实现互斥锁:package main
import (
"fmt"
"sync"
"time"
)
var mu sync.Mutex
counter int
func incrementCounter() {
mu.Lock()
defer mu.Unlock()
counter++
fmt.Println("Counter:", counter)
}
func main() {
for i := 0; i < 5; i++ {
go incrementCounter()
time.Sleep(1 * time.Second)
}
time.Sleep(2 * time.Second)
fmt.Println("Final Counter:", counter)
}
这些示例展示了如何在CentOS上使用Golang实现并发控制。你可以根据自己的需求选择合适的方法。