今日main.go
package main
import "fmt"
func do(i int) {
fmt.Println(i)
}
func main() {
do(1)
do(2)
do(3)
}
package main
import (
"fmt"
"time"
)
func do(i int) {
fmt.Println(i)
}
func main() {
go do(1)
go do(2)
go do(3)
time.Sleep(1 * time.Second)
}
package main
import (
"fmt"
"time"
)
func main() {
msg := "Let 's Go"
go func() {
fmt.Println(msg)
}()
msg = "hey"
time.Sleep(1 * time.Second)
}
會輸出"hey"
利用command
go run -race main.go
可以看到會檢查出哪些data有race condition
但用pi的環境 會出現下面的提示go run: -race is only supported on linux/amd64, linux/ppc64le, freebsd/amd64, netbsd/amd64, darwin/amd64 and windows/amd64
改寫成
package main
import (
"fmt"
"time"
)
func main() {
msg := "Let 's Go"
go func(input string) {
fmt.Println(input)
}(msg)
msg = "hey"
time.Sleep(1 * time.Second)
}
把要輸出的變數丟到goroutine的argument
package main
import (
"fmt"
"sync"
"time"
)
func do(i int, wg *sync.WaitGroup) {
fmt.Printf("start : %d\n", i)
time.Sleep(1 * time.Second)
fmt.Printf("end : %d\n", i)
wg.Done() // 減掉完成的job數
}
func main() {
wg := sync.WaitGroup{}
wg.Add(3)
go do(1, &wg)
go do(2, &wg)
go do(3, &wg)
wg.Wait() // 等待 以便看結果
fmt.Println("Done!!!!")
}