Skip to content

Sync Chapter: Add explanation on why the concurrent test fails #842

@laerson

Description

@laerson

Problem

A common pitfall for people learning about concurrency is why expressions like x = x + 1 can give unexpected results when it happens on multiple threads, since they look like a single instruction.

On the Sync chapter, the implementation of Inc() method isn't concurrently safe, but the reason why can be confusing for someone with no background on assembly:

func (c *Counter) Inc() {
	c.value++
}

Proposed Solution

Highlight that although c.value++ looks like a single instruction, the compiled instruction is actually similar to this:

tmp := x + 1 // instruction A
x = tmp      // instruction B

And then show how the counter can fail depending on the order the goroutines are executed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions