Member-only story

Golang

Prevent race condition in Go

using mutex.

Donald Le

--

Photo by Sincerely Media on Unsplash

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

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

before and after manipulate the data.

And that is it.

Hope it helps!

PEACE as always..

--

--

No responses yet