Sunday, October 2, 2022
HomeGolangmake Golang Packages thread-safe

make Golang Packages thread-safe


Concurrency is such a foundational functionality of the Go language that it’s easy to write down code that leverages a number of goroutines, generally with out even realizing.

For instance, when you’ve ever used the internet/http bundle to create an online service, you’ve used goroutines.

To deal with incoming HTTP site visitors, the HTTP Server will generate a goroutine for each connection and one per request with HTTP/2. These goroutines are clear to the person; you wouldn’t know they had been goroutines except you’ve learn the documentation.

This ease of use makes creating multi-goroutine purposes easy, it additionally makes it simple to create knowledge race circumstances.

Information Race with Golang

An information race is when a minimum of two threads or, on this case, goroutines attempt to entry the identical knowledge. For instance, one goroutine tries to learn knowledge whereas one other writes knowledge. This situation will trigger a Golang utility to panic and crash.

To elucidate higher, let’s say we created a easy World inside our utility that holds a counter.

var counter int

And an HTTP handler to increment this counter.

https://madflojo.medium.com/media/167e49b2d9d6d1b512f52e5b9bb0a1ff

As a result of every HTTP request initiates its goroutine, there’s a excessive probability that two goroutines (HTTP requests) will attempt to increment the counter concurrently. This may end in a panic situation.

What’s unlucky about this instance is that this knowledge race might not be discovered with primary testing. Information races are all about timing, two requests should increment the counter concurrently.

This instance bug can get previous commonplace testing.

Allow Information Race Detection with Golang

Nevertheless, Golang has a easy solution to detect knowledge race circumstances. Whereas executing assessments, it’s attainable to activate knowledge race detection utilizing the --race flag.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments