Using the Go keyword and Channel in Golang to implement parallelism

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Use of the Go keyword and channel

The Go keyword is used to create goroutine, which is the key to implementing concurrency. The use of the GO keyword is as follows:

//go 关键字放在方法调用前新建一个 goroutine 并让他执行方法体go GetThingDone(param1, param2);//上例的变种,新建一个匿名方法并执行go func(param1, param2) {}(val1, val2)//直接新建一个 goroutine 并在 goroutine 中执行代码块go {    //do someting...}

Because the goroutine is parallel in a multi-core CPU environment. If a block of code executes in multiple goroutine, we implement code parallelism. So the question is, how do we get the results in parallel? It's going to have to use the channel.

//resultChan 是一个 int 类型的 channel。类似一个信封,里面放的是 int 类型的值。var resultChan chan int//将 123 放到这个信封里面,供别人从信封中取用resultChan <- 123//从 resultChan 中取值。这个时候 result := 123result := <- resultChan

Using the Go keyword and channel for non-blocking calls

Blocking means that the caller must wait until the called code returns and cannot handle anything else. Instead of blocking calls, you do not have to wait and return immediately after the call. So how does the return value get? node. JS uses the callback method, and Golang uses the channel.

/** * 每次调用方法会新建一个 channel : resultChan, * 同时新建一个 goroutine 来发起 http 请求并获取结果。 * 获取到结果之后 goroutine 会将结果写入到 resultChan。 */func UnblockGet(requestUrl string) chan string {    resultChan := make(chan string)    go func() {        request := httplib.Get(requestUrl)        content, err := request.String()        if err != nil {            content = "" + err.Error()        }        resultChan <- content    } ()    return resultChan}

Because the new goroutine does not block the execution of the function's main process, calling the Unblockget method immediately gets a Resultchan return value. Once the goroutine is executed and the result is written to the Resultchan, the external can get the execution result from the Resultchan.

A very low parallel example

fmt.Println(time.Now())resultChan1 := UnblockGet("http://127.0.0.1/test.php?i=1")resultChan2 := UnblockGet("http://127.0.0.1/test.php?i=2")fmt.Println(<-resultChan1)fmt.Println(<-resultChan1)fmt.Println(time.Now())

The above two HTTP requests are in parallel in two goroutine. The total execution time is less than two request time and.

This example is just to reflect the use of Go and channel, there is a memory leak problem, do not do this online. Because the new channel is not close. Next time, write a higher-level one.

Simple implementation of HTTP multi GET

Type Remoteresult struct {Url string Result string}func remoteget (Requesturl string, Resultchan Chan Remoteresult) {Request: = Httplib. Newbeegorequest (Requesturl, "GET") request. SetTimeout (2 * time. Second, 5 * time. Second)//request. String () content, err: = Request. String () if err! = Nil {content = "" + Err. Error ()} Resultchan <-Remoteresult{url:requesturl, Result:content}}func multiget (URLs []string) []RemoteResult {FMT. Println (time. Now ()) Resultchan: = Make (chan Remoteresult, Len) defer close (Resultchan) var result []remoteresult//fm T.PRINTLN (Result) for _, url: = Range urls {Go remoteget (URL, Resultchan)} for i:= 0; I < Len (URLs); i++ {res: = <-resultchan result = Append (result, res)} FMT. Println (time. Now ()) return Result}func main () {urls: = []string{"http://127.0.0.1/test.php?i=13", "http://127.0.0 .1/test.php?i=14 "," http://127.0.0.1/test.php? i=15 "," http://127.0.0.1/test.php?i=16 "," http://127.0.0.1/test.php?i=17 "," http://127.0.0.1/test.ph P?i=18 "," http://127.0.0.1/test.php?i=19 "," http://127.0.0.1/test.php?i=20 "} Content: = Multiget (URLs ) FMT. PRINTLN (content)}

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.