This is a creation in Article, where the information may have evolved or changed.
When writing gobyexample, there is a problem as follows
Https://gobyexample.com/worker-pools
Package main 2 import ( 3 "FMT" 4 "Time" 5) 6 type Message struct { 7 ID int< C10/>8 Data string 9} func main () { ch1:=make (chan Message), Ch2:=make (Chan message
,19) i:=0;i<4;i++{ go func () { F1 (I,CH1,CH2) + } () + } for i:= 0;i<19;i++{ var m Message m.id=i ch1<-m for i:=0;i<19;i++{ Fmt. Println (<-CH2) +} , func f1 (id int, ch1 <-chan message,ch2 Chan <-message) {for msg: =range ch1{ msg.data=fmt. Sprintf ("%d", id) . Sleep (time. Second) ch2<-msg
Results
{0 4} {1 4} {2 4} {3 4} {4 4} {5 4} {6 4} {7 4} {8 4} {9 4} {10 4} {11 4} {12 4} {13 4} {14 4} {15 4} {16 4} {17 4} {18 4}
According to the truth, ID should be 0,1,2,3 How could it be 4?
Later, after Daniel pointed out some improvements
1 package Main 2 import ( 3 "FMT" 4 "Time" 5) 6 type Message struct { 7 ID int 8 Data string 9} func main () { ch1:=make (chan Message), Ch2:=make (Chan message
,19) for i:=0;i<4;i++{- go func () { F1 (I,CH1,CH2)-( ) . Sleep (time. Second) for i:=0;i<19;i++{, var m Message, m.id=i ( ch1<-m ) For i:=0;i<19;i++{ FMT. Println (<-CH2)-{<-chan}- func f1 (id int, ch1 message,ch2 <-message Chan =range) { $ for MSG ch1{ msg.data=fmt. Sprintf ("%d", id) time . Sleep (time. Second) ch2<-msg
There was a line of time when the Goroutine was created. Sleep (time. Second)
Results
{0 0} {1 1} {2 2} {3 3} {4 0} {5 1} {6 2} {7 3} {8 0} {9 1} {10 2} {11 3} {12 0} {13 1} {14 2} {15 3} {16 0} {17 1} {18 2}
I believe we all guessed why: it takes more than 4 times to create a goroutine for a loop when I create goroutine to fetch parameter values I'm already 4.
But the real reason for this situation, caused by the operating system, or the language itself, the specific details also look at Daniel pointing