This is a creation in Article, where the information may have evolved or changed.
28. Toad Notes Go language--concurrency simple example
Concurrency sample
Package Main
Import (
"FMT"
"Time"
)
Func Ready (W string, sec Int64) {
secs: =time. Duration (SEC) * time. Second
Time. Sleep (secs)
Fmt. Println (W, "is ready!")
}
Func Main () {
Goready ("Tee", 2)
Goready ("Coffee", 1)
Fmt. Println ("I ' mwaiting")
secs: =time. Duration (2) * time. Second
Time. Sleep (5* secs)
}
Output:
I ' mwaiting
Coffeeis ready!
Teeis ready!
Go syntax features
No shared memory, no memory lock, concurrent language-goroutines
Communication between Goroutines by the words ⾔ their own channels to deliver the message
In short, this ⼀ is useful for simply writing secure concurrent programs.
Parallel computing
Code:
Package Main
Import "FMT"
Func sum (values []int, Resultchan Chan int) {
Sum: =0
For _,value: = Range Values {
sum+= value
}
resultchan<-sum// sends the result of the calculation to Channel in
}
Func Main () {
values:= []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
resultchan:= make (chan int, 2)
Gosum (Values[:len (values)/2], Resultchan)
Gosum (Values[len (values)/2:], Resultchan)
sum1,sum2: = <-resultchan, <-resultchan// Receive Results
Fmt. Println ("Result:", Sum1, sum2, sum1+sum2)
}
Execution results
result:40 15 55