Go语言并发编程:从基础到Web应用实践
1. Go并发基础
1.1 同步goroutine
在Go语言中,我们可以使用通道(channel)来同步goroutine。以下是一个简单的示例代码:
package main import "fmt" import "time" func printNumbers2(w chan bool) { for i := 0; i < 10; i++ { time.Sleep(1 * time.Microsecond) fmt.Printf("%d ", i) } w <- true } func printLetters2(w chan bool) { for i := 'A'; i < 'A'+10; i++ { time.Sleep(1 * time.Microsecond) fmt.Printf("%c ", i) } w <- true } func main() { w1, w2 := make(chan bool), make(chan bool) go printNumbers2(w1) go printLetters2(w2) <-w1 <-w2