Go (Golang) sync.Mutex Tutorial

preview_player
Показать описание
Go (Golang) sync.Mutex Tutorial

In this episode we are going to see how easy is to use a sync.Mutex when working with shared resources and many go routines. When working with a variable that is shared and accessed by between different goroutines you have to keep in mind that access synchronisation is needed. The Go standard library has got you covered with the Mutex type coming from the sync package. The sync.Mutex stands for mutual exclusion lock and can be locked and used by only one go routine at a time. This will ensure that there won't be multiple go routines accessing, writing and messing around with the same data at the same time (causing an undetermined and unpredictable result)

When there is an imalance in the number of readers vs writers for a shared resource is good to keep in mind that it might be beneficial to use a RWMutex. Remember that with a RLock more than one reader can acquire a lock and read from the mutex, but only one can acquire the lock for writing. For the Mutex (standard mutex) only one go routine can acquire the lock whether is for reading or writing, so the access is more stringent and causes more resource contention (more go routines fighting to get access to the same resource)

Рекомендации по теме
Комментарии
Автор

Very good explanation, I like to watch your videos.

omarelkhatib
Автор

Technically there isn't a benefit to use go rountines with the initial example right? Since we have to sync the writes anyways. And very clear explanations!

GolangDojo