Javatpoint Logo
Javatpoint Logo

Go Race

A race condition occurs in Go when two or more goroutines try to access the same resource. It may happen when a variable attempts to read and write the resource without any regard to other routines.

Go Race Condition Example

Output:

foo:  0 Count:  1
bar:  0 Count:  1
foo:  1 Count:  2
foo:  2 Count:  3
foo:  3 Count:  4
bar:  1 Count:  2
foo:  4 Count:  5
foo:  5 Count:  6
foo:  6 Count:  7
bar:  2 Count:  3
bar:  3 Count:  4
bar:  4 Count:  5
foo:  7 Count:  8
foo:  8 Count:  9
bar:  5 Count:  6
bar:  6 Count:  7
foo:  9 Count:  10
bar:  7 Count:  8
bar:  8 Count:  9
bar:  9 Count:  10
last count value  10

As you can see in the above example, the count resource is accessed by 2 go routines. Each routine iterates to 10 times. In such case, the count variable should be 20 at last. But it is not so because it is simulating race condition.


Next TopicGo Mutex




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA