Go协程与协程池

1. Golang协程

  • golang和其它语言最大区别莫过于goroutine,也就是go的协程,example如下:
package main

import "fmt"
import "time"

func go_worker(name string) {
	for i:=0; i<10; i++ {
		fmt.Println("this is go worker :" , name)
	}
}

func main(){
	go go_worker("lineshen")
	go go_worker("glorialu")

	time.Sleep(time.Second*5) // print effective
	fmt.Println("main finished")
}

输出:

this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : lineshen
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
main finished

如果不用协程,上面代码应该三个线程运行,分别是主函数main和 两个函数。 使用协程之后,实际运行两个线程,这就是并发的好处。

Note当使用go启动协程之后,这2个函数就被切换到协程里面执行了,但是这时候主线程结束了,这2个协程还没来得及执行就会挂了!所以不在main中加time进行sleep就无法看到协程中的执行结果。

  • 多次运行,其结果可能如下:
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is go worker : glorialu
this is
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值