I will leave the Hello world, which is full of Go language features that I tweeted before, as a Qiita article.
It just implements the simple goal of displaying "Hello # number world" from 0 to 99 in parallel with goroutine. But it's interesting because it requires code that goes into the heart of the Go language.
If you do not use the channel, it will end in the middle, and if you do not pass the argument to goroutine properly, the numbers will overlap. Actually, when I tweeted, I didn't deal with these things, so I tried to do it seriously to make it an article this time, and noticed that it ended in the middle or something strange. Lol
Source
package main
import "fmt"
func main() {
max := 100
quit := make(chan bool, max)
for i := 0; i < max; i++ {
go func(j int) {
fmt.Printf("hello, #%v world\n", j)
quit <- true
}(i)
}
for i := 0; i < max; i++ {
<- quit
}
}
Execution result
Hello, #4 world
hello, #0 world
hello, #1 world
hello, #14 world
hello, #16 world
hello, #15 world
hello, #20 world
hello, #9 world
hello, #5 world
hello, #3 world
hello, #6 world
hello, #17 world
hello, #21 world
hello, #18 world
hello, #12 world
hello, #7 world
hello, #11 world
hello, #10 world
hello, #23 world
hello, #19 world
hello, #2 world
hello, #22 world
hello, #24 world
hello, #8 world
hello, #25 world
hello, #63 world
hello, #27 world
hello, #59 world
hello, #28 world
hello, #60 world
hello, #66 world
hello, #99 world
hello, #67 world
hello, #62 world
hello, #68 world
hello, #44 world
hello, #85 world
hello, #87 world
hello, #58 world
hello, #33 world
hello, #72 world
hello, #39 world
hello, #45 world
hello, #41 world
hello, #74 world
hello, #90 world
hello, #36 world
hello, #46 world
hello, #91 world
hello, #47 world
hello, #26 world
hello, #55 world
hello, #71 world
hello, #97 world
hello, #57 world
hello, #75 world
hello, #76 world
hello, #37 world
hello, #92 world
hello, #43 world
hello, #13 world
hello, #61 world
hello, #65 world
hello, #32 world
hello, #38 world
hello, #31 world
hello, #54 world
hello, #98 world
hello, #48 world
hello, #94 world
hello, #49 world
hello, #77 world
hello, #95 world
hello, #89 world
hello, #93 world
hello, #51 world
hello, #56 world
hello, #70 world
hello, #88 world
hello, #73 world
hello, #34 world
hello, #35 world
hello, #52 world
hello, #42 world
hello, #79 world
hello, #82 world
hello, #53 world
hello, #64 world
hello, #83 world
hello, #78 world
hello, #96 world
hello, #80 world
hello, #86 world
hello, #30 world
hello, #40 world
hello, #29 world
hello, #69 world
hello, #84 world
hello, #81 world
hello, #50 world
Recommended Posts