DEV Community

Discussion on: Making concurrent API requests in Go

Collapse
 
krusenas profile image
Karolis

This is not a safe way to use maps in Go :) the problem is with comicMap := make(map[int]*Comic) where you write to it from multiple goroutines in parallel. Consider either using sync.Map or just a sync.Mutex to synchronize writing results to the map.
If you have added a test for this and tried running them with --race flag then the compiler would have warned you.

Alternatively, you can also spawn a goroutine in the background that's just listening for results in a channel and all these goroutines that are doing HTTP requests could send results to the channel.

Anyway, there are several options how to solve this but this example might end up being a problem :)

Collapse
 
qainsights profile image
NaveenKumar Namachivayam ⚡

Can we use mutex in the above example to resolve the racing? :)