So, I was messing around with Go the other day, and I had this kinda silly idea: What if I made two Goroutines “fight” each other? Like, not really fight, but, you know, compete in some way. I called it “gorilla fights gorilla” because, well, Goroutines… gorillas… get it? Anyway, here’s how it went down.
The Setup
First, I needed a basic Go environment. I already had Go installed, so I just created a new directory and a new Go file called . Nothing fancy.
The “Fight”
I needed something for the Goroutines to compete over. I decided on a simple counter. One Goroutine would try to increment the counter, and the other would try to decrement it. A classic tug-of-war!
Here is the function that I create for running each Goroutine:
I spun up two Goroutines. Gorilla 1 was the incrementer, and Gorilla 2 was the decrementer. They both had access to the shared counter variable. I need to make sure only one Goroutine messes with the counter at a time, so each Goroutine add and minus by one.
After launching the Goroutines, I used the done channel to wait for both of them to finish. This is important, without this, the program would just exit before the Goroutines even got a chance to run!
The Results
I ran the code, and … it worked, and it would print who is doing what now! Each time I run it, I get a different result for who “wins”. Because, this is decided by the scheduler. Sometimes Gorilla 1 gets ahead, sometimes Gorilla 2 does. It’s all down to the whims of the Go scheduler.
Wrapping Up
So, that was my silly little “gorilla fights gorilla” experiment. It wasn’t groundbreaking, but it was a fun way to play around with Goroutines and see how they interact with shared resources. And it reinforced the importance of always remembering that concurrent programming can be unpredictable!