GO语言实现的简单的字母和数字交替输出

wcz3043 · · 1059 次点击
```go package main import ( "fmt" "runtime" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) runtime.GOMAXPROCS(1) limit := 26 //输出字母 go func() { defer wg.Done() for i := 0; i < limit; i++ { fmt.Printf("%c\n", 'a'+i) runtime.Gosched() } }() //输出数字 go func() { defer wg.Done() for i := 0; i < limit; i++ { fmt.Println(i) runtime.Gosched() } }() wg.Wait() } ```
#2
更多评论
```go package main import ( "fmt" "runtime" "sync" ) var zf []string = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} func PrintZF() { defer wg.Done() for i := 0; i < 26; i++ { fmt.Println(zf[i]) runtime.Gosched() } } func PrintN() { defer wg.Done() for i := 0; i < 26; i++ { fmt.Println(i) runtime.Gosched() } } var wg sync.WaitGroup func main() { runtime.GOMAXPROCS(1) wg.Add(1) go PrintZF() wg.Add(1) go PrintN() wg.Wait() } ```
#1
```go package main import ( "fmt" "sync" ) func main() { wg := &sync.WaitGroup{} wg.Add(2) limit := 26 numChan := make(chan int, 1) charChan := make(chan int, 1) charChan <- 1 go func() { defer wg.Done() for i := 0; i < limit; i++ { <-charChan fmt.Printf("%c\n", 'a'+i) numChan <- 1 } }() go func() { defer wg.Done() for i := 0; i < limit; i++ { <-numChan fmt.Println(i) charChan <- 1 } }() wg.Wait() close(charChan) close(numChan) } ```
#3