php小編魚仔為你解答並發golang程式設計中輸出不同的陣列長度的問題。在並發程式設計中,多個goroutine同時操作一個共享資源,可能會出現競爭條件導致結果不確定。當多個goroutine同時對陣列進行操作時,可能會導致陣列長度不同的情況。這是因為goroutine之間的執行順序是不確定的,可能會出現同時進行讀寫操作的情況,從而導致數組長度的不一致。要解決這個問題,可以使用互斥鎖或通道等機制來確保goroutine之間的同步與順序執行,從而得到確定的結果。
我正在用golang 編寫一個簡單的程式用於並發測試,但不明白capitalized
每次數組大小的不同輸出!
data := []rune{'a', 'b', 'c', 'd'} var capitalized []rune capit := func(r rune) { capitalized = append(capitalized, unicode.toupper(r)) fmt.printf("%c done!\n", r) } fmt.printf("before: %c\n", capitalized) for i := 0; i < len(data); i++ { go capit(data[i]) } time.sleep(100 * time.millisecond) fmt.printf("after: %c\n", capitalized)
輸出:
b done! a done! d done! c done! after: [d b c a]
a done! d done! c done! b done! after: [d b a]
d done! a done! c done! b done! after: [b]
d done! a done! c done! b done! after: [a b c]
d done! b done! a done! c done! After: [B C]
您存在數據競爭。
$ go run -race racer.go before: [] ================== warning: data race write at 0x00c000012018 by goroutine 8: main.main.func1() racer.go:14 +0xc4 main.main.func2() racer.go:20 +0x3e previous read at 0x00c000012018 by goroutine 7: main.main.func1() racer.go:14 +0x44 main.main.func2() racer.go:20 +0x3e goroutine 8 (running) created at: main.main() racer.go:20 +0x199 goroutine 7 (running) created at: main.main() racer.go:20 +0x199 ================== a done! ================== warning: data race write at 0x00c000012018 by goroutine 9: main.main.func1() racer.go:14 +0xc4 main.main.func2() racer.go:20 +0x3e previous write at 0x00c000012018 by goroutine 10: main.main.func1() racer.go:14 +0xc4 main.main.func2() racer.go:20 +0x3e goroutine 9 (running) created at: main.main() racer.go:20 +0x199 goroutine 10 (running) created at: main.main() racer.go:20 +0x199 ================== d done! b done! c done! after: [b c] found 2 data race(s) exit status 66 $
racer.go:
package main import ( "fmt" "time" "unicode" ) func main() { data := []rune{'a', 'b', 'c', 'd'} var capitalized []rune capIt := func(r rune) { capitalized = append(capitalized, unicode.ToUpper(r)) fmt.Printf("%c done!\n", r) } fmt.Printf("Before: %c\n", capitalized) for i := 0; i < len(data); i++ { go capIt(data[i]) } time.Sleep(100 * time.Millisecond) fmt.Printf("After: %c\n", capitalized) }
以上是為什麼並發golang程式設計中輸出不同的陣列長度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!