Golang多线程打印ABC
package main import ( "fmt" "sync" ) func ThreeG() { var ch1, ch2, ch3 = make(chan struct{}), make(chan struct{}), make(chan struct{}) var wg sync.WaitGroup wg.Add(3) go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch1 fmt.Println(s) ch2 <- struct{}{} } <-ch1 }("A") go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch2 fmt.Println(s) ch3 <- struct{}{} } }("B") go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch3 fmt.Println(s) ch1 <- struct{}{} } }("C") // 在向chan写入数据时,会阻塞当前协程,直到其他协程从该chan中读取了数据。 ch1 <- struct{}{} wg.Wait() } func NG(n int) { chanQueue := make([]chan struct{}, n) for i := 0; i < n; i++ { chanQueue[i] = make(chan struct{}) } var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { var preChan chan struct{} if i == 0 { preChan = chanQueue[n-1] } else { preChan = chanQueue[i-1] } curChan := chanQueue[i] go func(i byte, preChan, curChan chan struct{}, index int) { defer wg.Done() for k := 0; k < 5; k++ { <-preChan fmt.Printf("%c\n", i) curChan <- struct{}{} } if index == 0 { <-chanQueue[n-1] } }('A'+byte(i), preChan, curChan, i) } chanQueue[n-1] <- struct{}{} wg.Wait() fmt.Println("done") } func main() { }
package main
import (
"fmt"
"sync"
"time"
)
var S int
var wg sync.WaitGroup
func Sum(a int, b int) {
wg.Add(1)
defer wg.Done()
for ; a <= b; a++ {
S += a
}
}
func main() {
for i := 1; i <= 10; {
go Sum(i, i+100000)
i += 100000
}
wg.Wait()
time.Sleep(time.Millisecond * 1)
fmt.Println("累加结果为:", S)
}
posted on 2024-03-18 17:55 silenccfly 阅读(44) 评论(0) 编辑 收藏 举报