##前言
前一篇的一些討論後,接下來有一些更容易出錯的部分可以討論.主要focus Goroutine跟 defer
###Goroutine Closure
主要是這一篇部落格帶出的問題:
func main() {
done := make(chan bool)
values := []string{"a", "b", "c"}
for _, v := range values {
go func() {
fmt.Println(v)
done <- true
}()
}
// wait for all goroutines to complete before exiting
for _ = range values {
<-done
}
}
根據以上的部分,印出的結果不會是 “a”, “b”, “c”.而是 “c”, “c”, “c” 原因是 goroutine 變數會參照到go func 跑的時候.
如果修改成以下就可以避免這個問題:
func main() {
done := make(chan bool)
values := []string{"a", "b", "c"}
for _, v := range values {
go func(obj string) {
fmt.Println(obj)
done <- true
}(v)
}
// wait for all goroutines to complete before exiting
for _ = range values {
<-done
}
}
由於他的順序會是 go func(v) 之後才執行,所以其變數內容會先傳過去而不是跑道fmt.Println(v)才取得. 更多跟goroutinem與closure有關的資訊請看這裡Go: FAQ
參考資料
Effective Go: Channels
官方Effective Go文件,一定要熟讀.
Go FAQ: hat happens with closures running as goroutines?
A Go Gotcha: When Closures and Goroutines Collide
Preface Working on Android application development, you will need to have IAP (In-App Purchase) items. Normally it is simple, if your application is standalone not connect to any server. If you app need connect to server for IAP items (such as game server, database service …), it might have risk that here might be a fake app (or crack app) to fake the purchase command in your app to get privilege action or items. In this case, our server will need to do a sever-to-server side certification with Google Play. Android has done great documentation in their Android portal. But it separate into different part, so I am trying to summarized it here. Hope it help. Google Service Entrypoint - Google API When we want to communication with any Google Service, the only entry point is using Google API Console.. So, here let’s start to connect to Google API. According...
Preface: This article is a note about I study XMPP spec recent days. To maniplate a XMPP client, it might be easy to deal it with IP*WORKs 3rd party XMPP client. But it could not fulfil some custom request such as: Not response friend request immediatelly, once we got it. Handle roster (friend list) programmatically Maniplate VCard as custom information storage. In those case, we might need to handle XMPP XML commands to Ejabberd Ejabberd is a XMPP server(which twitter use it at first). It written by Erlang, it is powerful to handle multiple user connectivity. XMPP Command Both we could have two ways to manipulate XMPP, one by 3rd party XMPP framework. We will use IP*Work for a example which you can find sample code from web here. Another one is using basic XML send to XMPP server directly. Actually we still use IP*Works. sendCommand to send our XML...