golang goroutine、channel和select

前端之家收集整理的这篇文章主要介绍了golang goroutine、channel和select前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

goroutine

packagemain

import"fmt"
import"time"

funcprintn(idint){
	fori:=0;i<10;i++{
		fmt.Println(id,":",i)
	}
}


funcmain(){
	fori:=0;i<5;i++{
		goprintn(i)
	}
	fmt.Println("waiting...")
	time.Sleep(time.Second*3)
}
//执行结果:
waiting...
0:0
2:0
0:1
2:1
0:2
1:0
2:2
0:3
2:3
1:1
0:4
2:4
0:5
1:2
2:5
0:6
1:3
2:6
0:7
1:4
2:7
1:5
3:0
3:1
3:2
2:8
1:6
2:9
1:7
3:3
0:8
0:9
1:8
3:4
3:5
3:6
3:7
3:8
3:9
1:9
4:0
4:1
4:2
4:3
4:4
4:5
4:6
4:7
4:8
4:9


//如果把sleep去掉会怎么样?
packagemain

import"fmt"
//import"time"

funcprintn(idint){
	fori:=0;i<10;i++{
		fmt.Println(id,i)
	}
}


funcmain(){
	fori:=0;i<5;i++{
		goprintn(i)
	}
	fmt.Println("waiting...")
	//time.Sleep(time.Second*3)
}
//执行结果:
waiting...//原因是没有sleep,当main函数执行完会中断其他所有没执行完的任务

2、channel

packagemain

import"fmt"
//import"time"

funcprintn(idint,cchanint){
	fori:=0;i<10;i++{
		fmt.Println(id,i)
	}
	c<-0//将数值存到c
}


funcmain(){
	c:=make(chanint)//创建一个channel
	goprintn(1,c)
//	fori:=0;i<5;i++{
//		goprintn(i)
//	}
	fmt.Println("waiting...")
	//time.Sleep(time.Second*3)
	<-c//取出c得值
}
//执行结果:
waiting...
1:0
1:1
1:2
1:3
1:4
1:5
1:6
1:7
1:8
1:9

3、select

packagemain

import"fmt"
import"time"

funcfun1(cchanstring){
	for{
		c<-"fromfun1+"
		time.Sleep(time.Second*2)
	}
}

funcfun2(cchanstring){
for{
c<-"fromfun2-"
time.Sleep(time.Second*2)
}
}




funcmain(){
	c1:=make(chanstring)
	c2:=make(chanstring)
	gofun1(c1)
	gofun2(c2)
	for{
	select{
		casemsg1:=<-c1:
			fmt.Println(msg1)
		casemsg2:=<-c2:
fmt.Println(msg2)

	}
	}

}
//执行结果:

fromfun2-
fromfun1+
fromfun2-
fromfun1+
fromfun1+
fromfun2-
fromfun2-
fromfun1+
fromfun1+
fromfun2-
...........

猜你在找的Go相关文章