- Refs: TDD, Go Chinese Docs, Go Chinese Docs2
Put GO in front of target function is the only way to tell Go complier “start a new goroutine here”.
Concurrency Definition
The GO language naturally supports multiple concurrency. Concurrency means Having More Than One Thing In Process;
Goroutine Definition
An operation that does not block in GO will run in a separate process called a goroutine. What’s goroutine?
- Goroutine is the way in Go language to reach Concurrency level for programmer.
Similar concepts: Process, Threads, Coroutines;
- Process: the basic unit of resource allocation;
- Threads: the basic unit of program execution, like CPU ;
- Coroutine: lightweight threads that switch more quickly;
I don’t want to explain the detail difference between similar concepts, that has been finished with others; What we should know is Goroutine is most similar with Coroutine, while they are different with switcher;
- Coroutine: the switch with other coroutine is operate by operation system level, which would cost more execution resource;
- Goroutine: the switch with other goroutine is operate by user level, which would cost less execution resource;
Usage Goroutine
In go language, keyword go means a goroutine; just put the keyword go in front of target function; The Go complier will recognize it as goroutine; For example, there is a function which used to check URL status, called WebsiteChecker:
1 | func WebsiteChecker (url string) bool { |
Tips: the main function is (default) a goroutine; It is the parent goroutine of other goroutine in this process; If the parent goroutine is finished (killed or other finished states), the child goroutine will finished immediately; If child go routine is finished, the parent goroutine doesn’t matter;
WebsiteChecker Case
This case is form TDD tutorial. In this part, i just compare the performance after goroutine.
Basic Function Implement : Website Checker:
1 | func CheckWebsite(url string) bool { |
Use Website Checker with no goroutine:
1 | type WebsiteChecker func(string) bool |
Use Website Checker with goroutine
1 | type WebsiteChecker func(string) bool |
Compare with test
1 | func slowWebsiteChecker(_ string) bool { |
1 | go test -bench=. |
From above CLI
, before goroutine the process cost 2013483386 ns ~ 2 s
each loop; after goroutine the process cost 20275547 ns ~ 20 ms ~ 0.02s
each loop; A hundred times better performance;