Concurrency in Go: The Greedy vs Polite Worker Approaches to Using Locks

Kacper Bąk
5 min readApr 12, 2023

Concurrency is an important aspect of modern software development, and one of the most common challenges in concurrent programming is managing shared resources. One such shared resource is a lock, which can be used to synchronize access to a critical section of code, ensuring that only one thread can access it at a time. In this article, we will explore two different approaches to using a lock-in Go: the greedy worker approach and the polite worker approach.

Let’s start with the greedy worker approach. This approach involves holding onto the lock for the entirety of a worker’s work loop. In other words, a worker will acquire the lock at the beginning of its work loop, perform its work, and then release the lock at the end of its work loop. This approach is simple to implement and can be effective in some cases, but it has a significant downside: it can lead to contention for the lock, which can cause performance issues.

To illustrate this approach, let’s consider an example where we have two workers, each of which needs to perform some work that requires access to a shared resource. The GreedyWorker class below shows an example implementation of a worker that uses the greedy approach:

type GreedyWorker struct {
name string
mu *sync.Mutex
}

func (gw…

--

--

Kacper Bąk
Kacper Bąk

Written by Kacper Bąk

Software Engineer & Backend Developer

No responses yet