Sitemap

Sync Package In Go

2 min readMay 31, 2026

--

Press enter or click to view image in full size
sync package pic

well as you know power of golang relies on its concurrency programming and the ability to make two or more goroutines to do something simultaniously.

cuncurrency though comes with its unique and subtle problems.

for example imagine you have a variable which is shared among few goroutines fired at a certain time;normally you expect that variable gets change according to the programm but that wont happen.

lets have an example of such a scenario.
consider that we got a deposition function that adds a certain amount to user balance.
we get two deposition in a same time with amount of A and B , user balance is already C and we expect that user balance would be A + B + C after the programm which is concurrent right ?
but it may not ! it may get amount of A + C or A + B or A + B + C.
this happens because of the fact that variable was catched by the function at a certain time and that time could collide with others too.

so what is our solution for such scenarios ?

Get pooya dehghan’s stories in your inbox

Join Medium for free to get updates from this writer.

we use sync package in golang.

Mutual Exclusion :

lets fix stated problem above with our concurrency goroutine and channel knowledge , first of all we know that we could benefit channels to get programms and goroutines stop at certain part of the code .

we know if we get a unbuffered channel and want to read from it and it does not have any elements inside , it would block the entire programm ! well that comes handy for us here :) lets code it below

func main() {
myChannel := make(chan struct{} , 1)
balance := 0
func deposit(amnt int) {
myChannel <- struct{}{}
balance += amnt
<- myChannel
}
}

two great things happen here , first of all when deposit gets called twice in same time there will be stop at writing to channel because the first one has not finished the job yet and have not read from channel.

second we make sure the channel wont get out of element until balance has done its job and have added to certain amount.

this great tool comes handy so much that internally golang sync package has built its capability to handle shared variables same way.

var(
mu sync.Mutex
balance int
)

func deposit(amnt int) {
mu.Lock()
balance += amnt
mu.Unlock()
}

this neat syntax from sync package helps us to reduce boilerplate code and have a higher abstraction on channel solution we already discussed.

--

--

pooya dehghan
pooya dehghan

Written by pooya dehghan

0 followers

Im a software engineer with experience on Golang , Nodejs and backend engineering. I enjoy exploring AI and complex problems across domain of software and AI.