Skip to content

loop iterator variable error #49093

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
woodliu opened this issue Oct 21, 2021 · 1 comment
Closed

loop iterator variable error #49093

woodliu opened this issue Oct 21, 2021 · 1 comment

Comments

@woodliu
Copy link

woodliu commented Oct 21, 2021

What version of Go are you using (go version)?

1.17.2

$ go version

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

$ go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\liuch\AppData\Local\go-build
set GOENV=C:\Users\liuch\AppData\Roaming\go\env
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOROOT=C:\Program Files\Go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.17.2
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=NUL
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:\Users\liuch\AppData\Local\Temp\go-build463971690=/tmp/go-build -gno-record-gcc-switches
go env Output
$ go env

What did you do?

From golang wiki, i test "Using goroutines on loop iterator variables", the code as below,

    var vs []int
    for i := 0; i < 100; i++ {
        go func(val int) {
            vs = append(vs,val)
        }(i)
    }
    time.Sleep(time.Second * 3)
    sort.Ints(vs)
    fmt.Println(len(vs),vs)

What did you expect to see?

It shoud print the length of vs is 100, and the number of vs is from 0 ~ 99.

What did you see instead?

The length changes everthing i run the code, like
95 [0 1 2 6 7 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]

Why it lose some value, and what should i do if i want to match the expection? Thanks!

@woodliu
Copy link
Author

woodliu commented Oct 21, 2021

Because lack of lock....

@woodliu woodliu closed this as completed Oct 21, 2021
@woodliu woodliu reopened this Oct 21, 2021
@woodliu woodliu closed this as completed Oct 21, 2021
@golang golang locked and limited conversation to collaborators Oct 21, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants