在CentOS上使用Golang进行并发处理时,主要依赖于两个核心概念:goroutines和channels。以下是详细的并发处理技巧和示例代码:
Goroutines:
go
关键字可以轻松地启动一个新的goroutine。go func() {
fmt.Println("Hello from goroutine!")
}()
Channels:
ch := make(chan int)
go func() {
ch <- 42 // 发送数据到通道
}()
value := <-ch // 从通道接收数据
sync.WaitGroup:
Add
、Done
和Wait
方法来实现同步。var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d started\n", id)
time.Sleep(time.Second)
fmt.Printf("Goroutine %d finished\n", id)
}(i)
}
wg.Wait()
Mutex:
sync.Mutex
类型的变量来实现互斥锁。var counter int
var mutex sync.Mutex
func increment() {
mutex.Lock()
defer mutex.Unlock()
counter++
}
Context:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
done := make(chan bool)
go func() {
time.Sleep(3 * time.Second)
done <- true
}()
select {
case <-ctx.Done():
fmt.Println("Timeout")
case <-done:
fmt.Println("Completed")
}
以下是一个简单的示例,展示了如何在CentOS上使用Golang的并发特性:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d started\n", id)
time.Sleep(2 * time.Second)
fmt.Printf("Goroutine %d finished\n", id)
}(i)
}
wg.Wait()
fmt.Println("All goroutines finished")
}
在这个示例中,我们使用sync.WaitGroup
来确保主程序等待所有goroutines完成。我们创建了5个goroutines,每个goroutine都会打印开始和结束的消息,并在它们之间休眠2秒。
通过这些技巧和示例代码,你可以在CentOS上有效地使用Golang进行并发处理。根据具体需求,可以灵活运用这些技术来实现复杂的并发逻辑。