1.code exampleapp
公共方法code
func testDomain(ii string) { time.Sleep(time.Second * 4) fmt.Printf("pid: %d___point addr: %d___%s \n", GoID(), &ii, ii) }
func GoID() int { var buf [64]byte n := runtime.Stack(buf[:], false) idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0] id, err := strconv.Atoi(idField) if err != nil { panic(fmt.Sprintf("cannot get goroutine id: %v", err)) } return id }
2. 錯誤示範協程
var a []string
for i := 1; i < 5; i++ {
a = append(a, fmt.Sprintf("%d", i))
}
for _, i := range a { fmt.Printf("-----%s---\n", i) go func() { time.Sleep(time.Second * 4) testDomain(i) }() }
打印發現i每次地址都是同一個blog
協助每次先阻塞4秒get
4秒後 i的值是4, 這是協程中的方法testDomain開始工做,將i的值傳給本身的形參string
3. 正確示範class
for _, i := range a { fmt.Printf("-----%s---\n", i) go func(a string) { //time.Sleep(time.Second * 4) testDomain(a) }(i) }
這種操做會先將i的值傳遞給形參a,i的變化不會對testDomain方法的執行產生影響test
4. 完整代碼import
package main import ( "fmt" "runtime" "strconv" "strings" "time" ) func main() { var a []string for i := 1; i < 5; i++ { a = append(a, fmt.Sprintf("%d", i)) } for _, i := range a { fmt.Printf("-----%s---\n", i) go func(a string) { //time.Sleep(time.Second * 4) testDomain(a) }(i) go func() { time.Sleep(time.Second * 4) testDomain(i) }() fmt.Println(&i) time.Sleep(time.Second * 1) } time.Sleep(100 * time.Second) } func testDomain(ii string) { time.Sleep(time.Second * 4) fmt.Printf("pid: %d___point addr: %d___%s \n", GoID(), &ii, ii) } func GoID() int { var buf [64]byte n := runtime.Stack(buf[:], false) idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0] id, err := strconv.Atoi(idField) if err != nil { panic(fmt.Sprintf("cannot get goroutine id: %v", err)) } return id }