go并发学习
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func hello(i int) {
defer wg.Done()
fmt.Print(i, "hello hello\n")
}
func main() {
for i := 0; i < 6; i++ {
wg.Add(1) // 启动一个goroutine就登记+1
go hello(i)
}
fmt.Println("this is main done\n")
wg.Wait() //等的goroutine都结束
}
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
// func do(c chan int) {
// ret := <-c
// fmt.Println("接收成功", ret)
// defer wg.Done()
// }
func sendint(c chan int) {
for i := 0; i < 101; i++ {
c <- i //网管道放int
}
close(c)
defer wg.Done()
}
func sendandto(c, c1 chan int) {
for {
i, ok := <-c // 通道关闭后再取值ok=false
if !ok {
break
}
c1 <- i * i
}
close(c1)
defer wg.Done()
}
func main() {
// ch := make(chan int)
// wg.Add(1) // 启动一个goroutine就登记+1
// go do(ch)
// ch <- 10
// wg.Wait()
// fmt.Println("发送成功")
ch := make(chan int, 1)
ch1 := make(chan int, 1)
wg.Add(1) // 启动一个goroutine就登记+1
go sendint(ch)
wg.Add(1) // 启动一个goroutine就登记+1
go sendandto(ch, ch1)
for i := range ch1 { // 通道关闭后会退出for range循环
fmt.Println(i)
}
wg.Wait()
}
package main
import (
"fmt"
"runtime"
)
func send(str string) {
for i := 0; i < 3; i++ {
fmt.Printf("str:%v,%d\n", str, i)
if i > 0 {
runtime.Goexit()
}
}
}
func main() {
go send("php")
for i := 0; i < 3; i++ {
runtime.Gosched()
fmt.Printf("str:%v\n", "java")
}
fmt.Printf("str:%v\n", "end")
}
不逼一下自己,都不知道自己有多优秀!!!

浙公网安备 33010602011771号