what is data race ?

·

2 min read

what is data race ?

Lately, I have been exploring Golang; it's a fun language.

so i was reading about this concept of data race ...what is data race and when does it occur,How prevent it?

consider the below program:-



package main 


import (

    "sync"
    "fmt"

)


var w sync.WaitGroup 
var x int=0 // shared variable x

func main(){

    w.Add(100)

    for i := 0; i < 100; i++ {

       // spawning go routine 
        go func() {

            x++
            defer w.Done()

        }()
    }


    w.Wait() //wait for all go routines

    fmt.Println("final value of x :",x)
}

can you guess the value of x here ?

if your answer is 100 then you are wrong.

well the correct answer answer is that it depends on a lot of factors,The value if x here is not deterministic,it depends completely on the go runtime and how it schedules these go routines,also the number of go routines go will create depends upon the available resources your system has.

NOTE:the above go program doesn't create 100 go routines although it looks like it does.

The final value of x here fluctuates,so many go routines are trying to write and read the shared variable x.

If you try to run this program each time you will get a different value of x because multiple go routines are trying to access the same variable,this is called data race.

In my upcoming blogs ,I will discuss more about concurrency in go ,how to prevent data races ,mutexes and more.