Skip to content

x/website: Effective Go: bug in code example about concurrency #47357

@vitaly-zdanevich

Description

@vitaly-zdanevich

Here.

const numCPU = 4 // number of CPU cores

func (v Vector) DoAll(u Vector) {
    c := make(chan int, numCPU)  // Buffering optional but sensible.
    for i := 0; i < numCPU; i++ {
        go v.DoSome(i*len(v)/numCPU, (i+1)*len(v)/numCPU, u, c)
    }
    // Drain the channel.
    for i := 0; i < numCPU; i++ {
        <-c    // wait for one task to complete
    }
    // All done.
}

If len(v) is 10 doSome will receive
i = 0, n = 2
i = 2, n = 5
i = 5, n = 7
i = 7, n = 10

And because in doSome we have i < n we drop 10.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions