Go实现协程,实例

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

什么是协程?

  • 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 的协程机制是重要的特点,可以轻松开启上千万个协程.其他编程语言的并发机制一般是基于线程的,开启过多的线程,资源消耗大

猜你喜欢

转载自blog.csdn.net/weixin_44355591/article/details/107016128