28. Toad Notes Go language--concurrency simple example

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.