Prevent race condition in Go

Image for post
Image for post

When working with files or databases, or anything that relates to write permission, if we want to implement concurrency we need to implement lock. Because if we don’t, the data will be mess up by running concurrency.

So in Go, there is a couple of ways to do it like with mutex or using channel. In this post, we will use mutex for demonstration.

For example like we want to append data to the slice in Go when doing concurrency, first we need to define mutex

var (
mu = &sync.Mutex{}
data = make([]byte, 0)

Then in our go routine, we need to call

data = append(data, dataLocal...)
data = append(data, []byte("\n")...)

before and after manipulate the data.

And that is it.

Hope it helps!

PEACE as always..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store