在 Golang 中使用 Go 关键字和 Channel 实现并行
由于新建的 goroutine 不会阻塞函数主流程的执行,所以调用 UnblockGet 方法会立刻得到一个 resultChan 返回值。一旦 goroutine 执行完毕拿到结果就会写入到 resultChan 中,这时外部就可以从 resultChan 中获取执行结果。
<h2>一个很 low 的并行示例</h2> <pre><code>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())</code></pre>上面两个 http 请求是在两个 goroutine 中并行的。总的执行时间小于 两个请求时间和。
这个例子只是为了体现 go 和 channel 的用法,有内存泄漏问题,千万不要在线上这么搞。因为新建的 channel 没有 close。下次写一个更高级一点的。
<h2>简单的实现 http multi GET</h2> <pre><code class="golang">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(urls)) defer close(resultChan) var result []RemoteResult //fmt.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.php?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) }</code></pre> 到此这篇关于“在 Golang 中使用 Go 关键字和 Channel 实现并行”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!您可能感兴趣的文章:
在 Golang 中使用 Go 关键字和 Channel 实现并行
go语言并发编程
图解 Go 并发编程
Go 语言为什么这么快,带你详细了解Golang CSP并发模型
golang学习笔记(二)—— 深入golang中的协程
Go并发编程——channel
Go语言并发模型:以并行处理MD5为例
Go语言并发--传统锁与channel的选择
golang goroutine 通知_深入golang之---goroutine并发控制与通信
图解Go的channel底层原理