Go实现协程,实例

我会两种语言,一种写给程序执行,一种说给你听

什么是协程?

  • Go 协程是与其他函数或方法一起并发运行的函数或方法。Go 协程可以看作是轻量级线程。

如何快速启动一个协程

package main

import (
	"fmt"
	"strconv"
	"time"
)

func test() {
	for i := 1; i <= 10; i ++ {
		fmt.Println("test() hello, world" + strconv.Itoa(i))
		time.Sleep(time.Second)
	}
}

func main()  {
    // go test() 就是启动了
	go test()
	for i := 1; i <= 10; i ++ {
		fmt.Println("main() hello,Golang" + strconv.Itoa(i))
		time.Sleep(time.Second)
	}

}

运行结果

GOROOT=/usr/local/go #gosetup
main() hello,Golang1
test() hello, world1
test() hello, world2
main() hello,Golang2
main() hello,Golang3
test() hello, world3
main() hello,Golang4
test() hello, world4
test() hello, world5
main() hello,Golang5
main() hello,Golang6
test() hello, world6
test() hello, world7
main() hello,Golang7
main() hello,Golang8
test() hello, world8
test() hello, world9
main() hello,Golang9
main() hello,Golang10
test() hello, world10

Process finished with exit code 0

解释

运行结果表明,这个两个函数,即test()函数main()函数是交叉运行的,实现主要是通过go test()代码,我们只需要加上go就可以实现两个函数的并发

未开启协程

简单, 我们只需要把 go test()代码前的go去掉就好了,即:

func main()  {
    // 去掉 go 
	test()
	for i := 1; i <= 10; i ++ {
	.......
	....
	......

运行结果是这样的:

test() hello, world1
test() hello, world2
test() hello, world3
test() hello, world4
test() hello, world5
test() hello, world6
test() hello, world7
test() hello, world8
test() hello, world9
test() hello, world10
main() hello,Golang1
main() hello,Golang2
main() hello,Golang3
main() hello,Golang4
main() hello,Golang5
main() hello,Golang6
main() hello,Golang7
main() hello,Golang8
main() hello,Golang9
main() hello,Golang10

流程图:

协程图

小结

  • 相比线程而言,Go 协程的成本极低。堆栈大小只有若干 kb,并且可以根据应用的需求进行增减。
  • Golang 的协程机制是重要的特点,可以轻松开启上千万个协程.其他编程语言的并发机制一般是基于线程的,开启过多的线程,资源消耗大
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值