Go协程与协程池

时间:2024-10-11 07:25:46

1. Golang协程

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

import "fmt"
import "time"

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

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

	(*5) // print effective
	("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