Concurrency in Go (Part 2)
I made an article on concurrency in GoLang a year ago, Concurrency in Go (Part 1). I put "Part 1" on the title which caused people to wait for the second part. I also almost forgot to create the second part. Here we go.
There is a problem with concurrency. Functions that process data will have problems when running in multiple Goroutines. It happens because the data is shared and executed concurrently by multiple Goroutines. There is a conflict. It is called a race condition. A condition in which the behavior of the system depends on the sequence of events. We can solve it by using only a Goroutine or mutual exclusion.
|
|
Let's execute the code above. We can see that there is "1000" in our terminal.
|
|
You can try to benchmark that linear function to measure execution time on your computer, go test --bench=.
. Most computers only need less than 1 second.
The v
is the data that we want to process. We increment it. In any case, the data could be anything. Let's put the incrementation on the Goroutine for an example.
|
|
We use WaitGroup
to wait for a group of Goroutines to finish the execution. We add 1 to the WaitGroup
and decrement it on the Increment
function. It executes the next step when it turns 0.
You can try it on your local machine multiple times. It would be a random number and never be 1000. As I mentioned above, it is a race condition.
|
|
We solve it by using the mutual exclusion method, or Mutex in GoLang. You can try to run the code above. We only need a second to wait for the Goroutine to finish. The result will be always 1000.
References
Related Articles
- Deploy a Go App to AWS EC2
- A Simple Blog with Go
- Pemrograman Dasar Menggunakan GoLang
- Go Module
- Go Template