View profile

Concurrency in Go #2 - The sync Package - Software Shots

Concurrency in Go #2 - The sync Package - Software Shots
By Karn • Issue #13 • View online
Hi there 👋 If you’ve worked in languages that primarily handle concurrency through memory access synchronization, the types in this packages will likely be faimiliar to you.

Starting with a quick revision on waitgroups.
We went through this a bit in the last shot. You can think of a WaitGroup as a concurrent safe counter.
Mutex and RWMutex
Mutex stands for Mutual Exclusion and is a way to guard critical sections of your program. Critical section is an area of your program that requires exclusive access to a shared resource. You are responsble for coordinating access to this memory by guarding access to it with a mutex.
Calling Unlock in defer ensures it is called even when panicing. Failing to do so will probably cause a deadlock.
sync.RWMutex is conceptually the same thing as a Mutex: it guards access to memory, but RWMutex gives you a little bit more control. You can request a lock for reading, and you will be granted access unless the lock is being held for writing.
Here’s a quick example with a producer that is less active whereas the numerous consumers the code creates.
If we have a look at the output, you’ll see that reducing the cross-section of our critical section really only begins to pay off around 16384 readers.
This will vary depending on what your critical section is doing, but it’s usually advisable to use RWMutex instead of Mutex when it logically makes sense.
That’s about it, I’ll recommend playing around with the code, whenever you have time. We’ll go into more types like Cond, Pool, Once from the sync package in the next shot.
Have an awesome week. 👋
Did you enjoy this issue?
By Karn

I build and create things. As of now, I work as a Software Engineer at SendX/SendPost.

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue
Gyan Karn, Delhi, India - 110039