为什么在并发Golang编程中输出不同的数组长度?

6rqinv9w  于 2023-06-27  发布在  Go
关注(0)|答案(1)|浏览(88)

我正在用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完成!A完成!完成了!完成了!After:[D B C A]
完成!完成!C完成!B完成!After:[D B A]
完成了!完成了!C完成!B完成!之后:[B]
完成了!完成了!C完成!B完成!After:[A B C]
D完成!B完成!A完成!C完成!之后:[B C]

vlurs2pr

vlurs2pr1#

Go: Data Race Detector
你有数据竞赛。

$ 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)
}

相关问题