在開發過程中,當需要同時處理多個操作時,開發者經常面臨同步和異步兩種處理方式的選擇。
在同步處理方式中,任務按順序一個接一個地執行。每個任務必須在下一個任務開始之前完成。這意味著如果某個任務需要花費大量時間來完成,它可能會阻塞后續任務的執行,導致潛在的性能瓶頸。
一個簡單的現實生活中的例子是兩個人在喝啤酒時進行對話。一個人說一些話并提問,另一個人根據情況回應,然后反過來...
在下面的示例中,每個URL調用必須完成其整個請求-響應周期并提供響應或錯誤,以便可以進行后續的URL調用。
package mainimport ( "fmt" "net/http")func makeUrlCall(url string) { _, err := http.Get(url) if err != nil { fmt.Println("Got error in connecting to url: ", url) } fmt.Println("Got the response from our url: ", url)}func main() { fmt.Println("Welcome here !!") fmt.Println() //slice of urls urlSlice := []string{ "https://www.baidu.com", "https://www.csdn", "https://www.runoob.com", } for idx, url := range urlSlice { fmt.Println("Calling url on index: ", idx) makeUrlCall(url) } fmt.Println() fmt.Println("End of sync processing !!") return}
輸出:
Welcome here !!Calling url on index: 0Got the response from our url: https://www.baidu.comCalling url on index: 1Got the response from our url: https://www.csdnCalling url on index: 2Got the response from our url: https://www.runoob.comEnd of sync processing !!
在異步處理方式中,任務獨立并同時執行。這意味著程序在一個任務完成之前不會等待它繼續下一個任務。在Golang中,可以使用Goroutines和Go運行時來實現異步編程。
一個簡單的現實生活中的例子是去汽車修理店。一旦工程師處理完其他任務,他們會處理你的任務。在此期間,你可以做其他重要的事情,直到你的汽車被取走并修好。
在下面的示例中,每個URL調用將通過goroutine在自己的線程中進行,并根據需要處理響應。
package mainimport ( "fmt" "net/http" "sync")func makeUrlCall(url string) { _, err := http.Get(url) if err != nil { fmt.Println("Got error in connecting to url: ", url) } fmt.Println("Got the response from our url: ", url)}func main() { fmt.Println("Welcome here !!") fmt.Println() //slice of urls urlSlice := []string{ "https://www.baidu.com", "https://www.csdn", "https://www.runoob.com", } var wg sync.WaitGroup for _, u := range urlSlice { wg.Add(1) //all the url's to get error/response are called in their own separate thread via goroutines go func(url string) { defer wg.Done() makeUrlCall(url) }(u) } wg.Wait() fmt.Println() fmt.Println("End of sync processing !!") return}
輸出:
Welcome here !!Got the response from our url: https://www.baidu.comGot the response from our url: https://www.runoob.comGot the response from our url: https://www.csdnEnd of sync processing !!
如果我們在切片中添加更多的URL并進行更多的HTTP get請求,比較兩種方式的性能。
本文鏈接:http://www.tebozhan.com/showinfo-26-17164-0.html提升應用性能:Go中的同步與異步處理
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 一年經驗,你讓我精通微服務開發,過分嗎?
下一篇: 聊聊接口重試機制的幾種解決方案